package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysParamSearchOutputDto;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacTestResult;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bac.BacTestResultMapper;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.request.AddLabMaininfo;
import com.ysd.lis.request.DeleteResultParam;
import com.ysd.lis.request.Params;
import com.ysd.lis.request.RptResultDto;
import com.ysd.lis.request.lab.LabFeeItemRptresultDto;
import com.ysd.lis.request.lab.LabRptresultGroupDto;
import com.ysd.lis.request.lab.LabRptresultTempDto;
import com.ysd.lis.request.lab.LabTextResultDto;
import com.ysd.lis.request.men.ChannelInfoDto;
import com.ysd.lis.request.men.ChannelInfoVo;
import com.ysd.lis.request.men.TestInfoDto;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.lis.service.lab.LabResultAmendmentService;
import com.ysd.lis.service.lab.LabRptGroupService;
import com.ysd.lis.service.lab.LabRptresultService;
import com.ysd.lis.util.lab.CalcItemFormulaReplcae;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2023-12-26
 */
@Service
public class LabRptresultServiceImpl extends ServiceImpl<LabRptresultMapper, LabRptresult> implements LabRptresultService {

    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    LabRptresultMapper labRptresultMapper;

    @Autowired
    LabRptresultQMapper labRptresultQMapper;

    @Autowired
    LabItemDictMapper labItemDictMapper;

    @Autowired
    LabItemDictReferMapper labItemDictReferMapper;

    @Autowired
    LabItemDictCriticalMapper labItemDictCriticalMapper;

    @Autowired
    LabTransResultMapper labTransResultMapper;

    @Autowired
    LabTextResultMapper labTextResultMapper;

    @Autowired
    LabFeeitemVsItemDictMapper labFeeitemVsItemDictMapper;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    LabChannelMapper labChannelMapper;

    @Autowired
    LabItemDictSpecialRulesMapper labItemDictSpecialRulesMapper;

    @Autowired
    LabTemplateDetailMapper labTemplateDetailMapper;

    @Autowired
    private LabRptGroupService labRptGroupService;

    @Autowired
    LabCriticalReportMapper labCriticalReportMapper;

    @Autowired
    RedisSysParamHelper redisSysParamHelper;

    @Autowired
    LabRptresultCalcServiceImpl labRptresultCalcService;

    @Autowired
    LabResultAmendmentService labResultAmendmentService;
    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Autowired
    LabReqdetailMapper labReqdetailMapper;


    @Override
    public Result insertRptResult(LabRptresult labRptresult) throws JsonProcessingException {
        SysUser sysUser = RedisUserManager.getUser();
        LabMaininfo mainInfoEntry = null;
        /*创建结果时 如果没有检验记录自动创建一条*/
        if (StringUtils.isEmpty(labRptresult.getMaininfoId())) {
            AddLabMaininfo addMainInfo = new AddLabMaininfo();
            if (StringUtils.isEmpty(labRptresult.getRptGroup())) {
                return Result.fail("请选择报告单元");
            }
            if (BeanUtil.isEmpty(labRptresult.getSampleda())) {
                return Result.fail("请选择检验日期");
            }
            if (StringUtils.isEmpty(labRptresult.getSampleNo())) {
                return Result.fail("请输入标本号");
            }
            addMainInfo.setRptGroup(labRptresult.getRptGroup());
            addMainInfo.setSampleda(labRptresult.getSampleda());
            addMainInfo.setSampleNo(labRptresult.getSampleNo());
            addMainInfo.setReqNo("");


            Result addMainInfoRes = labMaininfoService.insertMaininfoByReqNo(addMainInfo);

            if (!addMainInfoRes.getStatus().get("code").equals(1)) {
                return addMainInfoRes;
            }
            mainInfoEntry = (LabMaininfo) addMainInfoRes.getData();
            labRptresult.setMaininfoId(mainInfoEntry.getId());
        } else {
            MPJLambdaWrapper<LabMaininfo> mainMapper = new MPJLambdaWrapper<>();
            mainMapper.eq(LabMaininfo::getDelFlag, 0);
            Timestamp timestamp = new Timestamp(labRptresult.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            mainMapper.ge(LabMaininfo::getSampleda, startTime);
            mainMapper.le(LabMaininfo::getSampleda, endTime);
            mainMapper.eq(LabMaininfo::getRptGroup, labRptresult.getRptGroup());
            mainMapper.eq(LabMaininfo::getSampleNo, labRptresult.getSampleNo());
            List<LabMaininfo> mainLst = labMaininfoMapper.selectList(mainMapper);
            mainInfoEntry = mainLst.isEmpty() ? null : mainLst.get(0); //labMaininfoService.getById(labRptresult.getMaininfoId());
            if (BeanUtil.isEmpty((mainInfoEntry))) {
                return Result.fail("查无检验记录");
            }
            if (!BeanUtil.isEmpty(mainInfoEntry.getIsChk()) && mainInfoEntry.getIsChk().compareTo(new BigDecimal(0)) > 0) {
                return Result.fail("当前标本已审核,不允许再次新增/修改结果!");
            }
            labRptresult.setMaininfoId(mainInfoEntry.getId());
        }

        /*查询是否已经存在该项目，如果存在，在修改结果，如果不存在，则插入结果*/
        LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();

        Timestamp timestamp = new Timestamp(labRptresult.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        _labrptresultmapper.ge(LabRptresult::getSampleda, startTime);
        _labrptresultmapper.le(LabRptresult::getSampleda, endTime);
        _labrptresultmapper.eq(LabRptresult::getRptGroup, labRptresult.getRptGroup());
        _labrptresultmapper.eq(LabRptresult::getSampleNo, labRptresult.getSampleNo());
        _labrptresultmapper.eq(LabRptresult::getItemNo, labRptresult.getItemNo());
        _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);

        List<LabRptresult> rptresultArr = labRptresultMapper.selectList(_labrptresultmapper);

        LabRptresult rptresultlist = rptresultArr.isEmpty() ? null : rptresultArr.get(0);
        LabResultAmendment labResultAmendment = new LabResultAmendment();
        if (!BeanUtil.isEmpty(rptresultlist)) {
            //塞入记录表
            if (!labRptresult.getTestResult().equals(rptresultlist.getTestResult())) {
                labResultAmendment.setMaininfoId(rptresultlist.getMaininfoId());
                labResultAmendment.setWlResult(rptresultlist.getId());
                labResultAmendment.setItemNa(rptresultlist.getItemNa());
                labResultAmendment.setItemNo(rptresultlist.getItemNo());
                labResultAmendment.setOriginalResult(rptresultlist.getTestResult());
                labResultAmendment.setAmendedResult(labRptresult.getTestResult());
                labResultAmendment.setAmendedDate(new Timestamp(new Date().getTime()));
                labResultAmendment.setAmendedUserId(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getId() : "");
                labResultAmendment.setAmendedUserName(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getRealname() : "");
                labResultAmendmentService.save(labResultAmendment);
            }
            rptresultlist.setTestResult(labRptresult.getTestResult());
            //如果结果为空或者结果为提取后的项目默认值，则isresult = 0

            if(ToolsUtils.isEmpty(rptresultlist.getTestResult())){
                rptresultlist.setIsResult(0);
            }else {
                //提取后项目默认值
                String tqhxmmrz = "";
                try {
                    SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(labRptresult.getOrgId(), "tqhxmmrz", labRptresult.getRptGroup(), null);
                    tqhxmmrz = paramResult.getValueStr();
                } catch (Exception e) {
                    //TODO
                }

                if(ToolsUtils.isNotEmpty(tqhxmmrz)&&tqhxmmrz.equals(rptresultlist.getTestResult())){
                    rptresultlist.setIsResult(0);
                }else {
                    rptresultlist.setIsResult(1);
                }

            }
            rptresultlist.setIsBigText(labRptresult.getIsBigText());
            int iupt = labRptresultMapper.updateById(rptresultlist);
            if (iupt <= 0) {
                return Result.fail("更新已有检测项目结果失败");
            }
        } else {
            int i = labRptresultMapper.insert(labRptresult);
            if (i <= 0) {
                return Result.fail("新增检测项目结果失败");
            }
        }
        //插入更新后 重新获取检验报告结果
        MPJLambdaWrapper<LabRptresult> __labrptresultmapper = new MPJLambdaWrapper<>();
        __labrptresultmapper.selectAll(LabRptresult.class);
        __labrptresultmapper.selectAs("itmdict", LabItemDict::getItemNo, LabRptresult::getItemNo);
        __labrptresultmapper.selectAs(LabItemDict::getIsCalcItem, LabRptresult::getIsCalcItem);
        __labrptresultmapper.selectAs("itmdict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
        __labrptresultmapper.leftJoin(LabItemDict.class, "itmdict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
        __labrptresultmapper.eq(LabRptresult::getSampleNo, labRptresult.getSampleNo());


        __labrptresultmapper.ge(LabRptresult::getSampleda, startTime);
        __labrptresultmapper.le(LabRptresult::getSampleda, endTime);
        __labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        __labrptresultmapper.eq(LabRptresult::getRptGroup, mainInfoEntry.getRptGroup());
        __labrptresultmapper.orderByAsc(LabRptresult::getDisplayOrder);

        List<LabRptresult> rptResults = labRptresultMapper.selectJoinList(LabRptresult.class, __labrptresultmapper);

        LabMaininfo finalMainInfoEntry = mainInfoEntry;

        /*【【【【【【【【【【-----------------------V0版本------------------------】】】】】】】】】】*/
        //Long st = System.currentTimeMillis();

        /*文字结果处理*/
        //CalcTextResult(finalMainInfoEntry, rptResults);
        //printLog(rptResults);
        /*结果二次处理*/
        //CalcTransResult(finalMainInfoEntry, rptResults);
        //printLog(rptResults);

        //计算项目处理
        //CalcFormulaItemResult(finalMainInfoEntry, rptResults);
        //printLog(rptResults);

        /*计算危急值*/
        //CalcItemDictCritical(finalMainInfoEntry, rptResults);
        //printLog(rptResults);

        /*计算结果标识特殊规则*/
        //CalcItemDictSpecialRules(finalMainInfoEntry, rptResults);

        //Long st2 = System.currentTimeMillis();

        //System.out.println("计算结果总共耗时：" + (st2 - st) + "ms");
        /*【【【【【【【【【【-----------------------------------------------】】】】】】】】】】*/

        /*【【【【【【【【【【-----------------------V1版本------------------------】】】】】】】】】】*/
        Long st = System.currentTimeMillis();
        /*查询报告项目备用*/
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, finalMainInfoEntry.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        /*文字结果*/
        labRptresultCalcService.CalcTextResultV1(finalMainInfoEntry, rptResults, itemList);
        /*结果二次处理*/
        labRptresultCalcService.CalcTransResultV1(finalMainInfoEntry, rptResults, itemList);
        /*计算项目处理*/
        labRptresultCalcService.CalcFormulaItemResultV1(finalMainInfoEntry, rptResults, itemList);
        /*计算危急值*/
        labRptresultCalcService.CalcItemDictCriticalV1(finalMainInfoEntry, rptResults, itemList);
        /*计算结果标识特殊规则*/
        labRptresultCalcService.CalcItemDictSpecialRulesV1(finalMainInfoEntry, rptResults);

        /*计算完成 更新 结果*/
        //this.saveOrUpdateBatch(rptResults);

        for (LabRptresult rptresult : rptResults){
            LambdaQueryWrapper<LabRptresult> _labrptresultQuery = new LambdaQueryWrapper<>();
            _labrptresultQuery.eq(LabRptresult::getSampleNo, rptresult.getSampleNo())
                    .eq(LabRptresult::getRptGroup, rptresult.getRptGroup())
                    .eq(LabRptresult::getItemNo, rptresult.getItemNo())
                    .eq(LabRptresult::getDelFlag, 0)
                    .eq(LabRptresult::getSampleda, rptresult.getSampleda());
            this.saveOrUpdate(rptresult, _labrptresultQuery);
        }


        //如果finalLabMaininfo下得所有rptResults得isResult为1，则finalLabMaininfo得isResult为1
        List<LabRptresult> _lst = rptResults.stream().filter(p -> (ToolsUtils.isEmpty(p.getIsResult()) || p.getIsResult() == 0)).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(_lst)) {
            finalMainInfoEntry.setIsResult(1);
        } else {
            finalMainInfoEntry.setIsResult(0);
        }

        List<LabRptresult> alarmList = rptResults.stream().filter(p -> ToolsUtils.isNotEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(alarmList)) {
            finalMainInfoEntry.setIsAlarm(1);
            int ri = labMaininfoMapper.updateById(finalMainInfoEntry);
        } else {
            finalMainInfoEntry.setIsAlarm(0);
            int rii = labMaininfoMapper.updateById(finalMainInfoEntry);
        }
        Long st2 = System.currentTimeMillis();
        System.out.println("调优==========》计算结果总共耗时：" + (st2 - st) + "ms");
        /*【【【【【【【【【【----------------------------------------------------】】】】】】】】】】*/


        String itmNo = labRptresult.getItemNo();
        List<LabRptresult> rptresultList = rptResults.stream().filter(p -> p.getItemNo().equals(itmNo)).collect(Collectors.toList());
        if (!BeanUtil.isEmpty(rptresultList) && !rptresultList.isEmpty()) {
            labRptresult = rptresultList.get(0);
        }

        return Result.succ(1, "成功", labRptresult);
    }


    @Override
    public Result saveImgTxtRptValue(LabRptresult labRptresult) throws JsonProcessingException {
        if (StringUtils.isEmpty(labRptresult.getRptGroup())) {
            return Result.fail("请选择报告单元");
        }
        if (BeanUtil.isEmpty(labRptresult.getSampleda())) {
            return Result.fail("请选择检验日期");
        }
        if (StringUtils.isEmpty(labRptresult.getSampleNo())) {
            return Result.fail("请输入标本号");
        }
        LabMaininfo mainInfoEntry = new LabMaininfo();
        if (StringUtils.isEmpty(labRptresult.getMaininfoId())) {
            AddLabMaininfo addMainInfo = new AddLabMaininfo();
            addMainInfo.setRptGroup(labRptresult.getRptGroup());
            addMainInfo.setSampleda(labRptresult.getSampleda());
            addMainInfo.setSampleNo(labRptresult.getSampleNo());
            addMainInfo.setReqNo("");
            Result addMainInfoRes = this.addMaininfoByReqNo(addMainInfo);

            if (!addMainInfoRes.getStatus().get("code").equals(1)) {
                return addMainInfoRes;
            }
            mainInfoEntry = (LabMaininfo) addMainInfoRes.getData();
        } else {
            mainInfoEntry = this.labMaininfoMapper.selectById(labRptresult.getMaininfoId());
        }
        labRptresult.setMaininfoId(mainInfoEntry.getId());
        LambdaQueryWrapper<LabRptresult> lambdaQueryWrappers = new LambdaQueryWrapper<>();

        lambdaQueryWrappers.eq(LabRptresult::getSampleNo, labRptresult.getSampleNo());
        lambdaQueryWrappers.eq(LabRptresult::getRptGroup, labRptresult.getRptGroup());
        lambdaQueryWrappers.eq(LabRptresult::getSampleda, labRptresult.getSampleda());
        lambdaQueryWrappers.eq(LabRptresult::getItemNo, labRptresult.getItemNo());
        lambdaQueryWrappers.eq(LabRptresult::getMaininfoId, mainInfoEntry.getId());
        lambdaQueryWrappers.eq(LabRptresult::getDelFlag, 0);
        this.saveOrUpdate(labRptresult, lambdaQueryWrappers);

        return Result.succ(1, "成功", labRptresult);
    }

    @Override
    @Transactional
    public Result saveImgTxtRptValueBatch(List<LabRptresult> labRptresults) throws JsonProcessingException {
        if (labRptresults.size() == 0) {
            return Result.fail("无上传数据");
        }

        LabRptresult labRptresult = labRptresults.get(0);

        if (StringUtils.isEmpty(labRptresult.getRptGroup())) {
            return Result.fail("请选择报告单元");
        }
        if (BeanUtil.isEmpty(labRptresult.getSampleda())) {
            return Result.fail("请选择检验日期");
        }
        if (StringUtils.isEmpty(labRptresult.getSampleNo())) {
            return Result.fail("请输入标本号");
        }
        LabMaininfo mainInfoEntry = null;
        if (StringUtils.isEmpty(labRptresult.getMaininfoId())) {
            AddLabMaininfo addMainInfo = new AddLabMaininfo();
            addMainInfo.setRptGroup(labRptresult.getRptGroup());
            addMainInfo.setSampleda(labRptresult.getSampleda());
            addMainInfo.setSampleNo(labRptresult.getSampleNo());
            addMainInfo.setReqNo("");
            Result addMainInfoRes = this.addMaininfoByReqNo(addMainInfo);

            if (!addMainInfoRes.getStatus().get("code").equals(1)) {
                return addMainInfoRes;
            }
            mainInfoEntry = (LabMaininfo) addMainInfoRes.getData();
        } else {
            mainInfoEntry = this.labMaininfoMapper.selectById(labRptresult.getMaininfoId());
        }
        if (ToolsUtils.isNotEmpty(mainInfoEntry)) {
            labRptresult.setMaininfoId(mainInfoEntry.getId());
            LambdaQueryWrapper<LabRptresult> lambdaQueryWrappers = new LambdaQueryWrapper<>();

            lambdaQueryWrappers.eq(LabRptresult::getSampleNo, labRptresult.getSampleNo());
            lambdaQueryWrappers.eq(LabRptresult::getRptGroup, labRptresult.getRptGroup());
            lambdaQueryWrappers.eq(LabRptresult::getSampleda, labRptresult.getSampleda());
            lambdaQueryWrappers.eq(LabRptresult::getItemNo, labRptresult.getItemNo());
            lambdaQueryWrappers.eq(LabRptresult::getMaininfoId, mainInfoEntry.getId());
            lambdaQueryWrappers.eq(LabRptresult::getDelFlag, 0);
            for (LabRptresult p : labRptresults) {
                p.setMaininfoId(mainInfoEntry.getId());
                this.saveOrUpdate(p, lambdaQueryWrappers);
            }
            return Result.succ(1, "成功", labRptresult);
        } else {
            return Result.fail("写入值失败！");
        }
    }


    @Override
    public Result updateResult(LabMaininfo labMaininfo) {

        // SysUser sysUser = RedisUserManager.getUser();

        if (BeanUtil.isEmpty((labMaininfo))) {
            return Result.fail("查无检验记录");
        }

        if (!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().compareTo(new BigDecimal(0)) > 0) {
            return Result.fail("当前标本已审核,不允许再次新增/修改结果!");
        }

        List<LabRptresult> rptresultArr = labMaininfo.getResultList();

        if (BeanUtil.isEmpty(rptresultArr)) {
            return Result.succ(labMaininfo);
        }


        // LabRptresult rptresult = rptresultArr.isEmpty() ? null : rptresultArr.get(0);
        // LabResultAmendment labResultAmendment = new LabResultAmendment();
        //
        // if (!BeanUtil.isEmpty(rptresult)) {
        //塞入记录表
        // if (!labRptresult.getTestResult().equals(rptresult.getTestResult())){
        //     labResultAmendment.setMaininfoId(rptresult.getMaininfoId());
        //     labResultAmendment.setWlResult(rptresult.getId());
        //     labResultAmendment.setItemNa(rptresult.getItemNa());
        //     labResultAmendment.setItemNo(rptresult.getItemNo());
        //     labResultAmendment.setOriginalResult(rptresult.getTestResult());
        //     labResultAmendment.setAmendedResult(labRptresult.getTestResult());
        //     labResultAmendment.setAmendedDate(new Timestamp(new Date().getTime()));
        //     labResultAmendment.setAmendedUserId(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getId() : "");
        //     labResultAmendment.setAmendedUserName(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getRealname() : "");
        //     labResultAmendmentService.save(labResultAmendment);
        // }
        // rptresult.setTestResult(labRptresult.getTestResult());
        //     int iupt = labRptresultMapper.updateById(rptresult);
        //     if (iupt <= 0) {
        //         return Result.fail("更新已有检测项目结果失败");
        //     }
        // }
        // else {
        //     int i = labRptresultMapper.insert(labRptresult);
        //     if (i <= 0) {
        //         return Result.fail("新增检测项目结果失败");
        //     }
        // }


        Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");

        //插入更新后 重新获取检验报告结果
        MPJLambdaWrapper<LabRptresult> __labrptresultmapper = new MPJLambdaWrapper<>();
        __labrptresultmapper.selectAll(LabRptresult.class);
        __labrptresultmapper.selectAs("itmdict", LabItemDict::getItemNo, LabRptresult::getItemNo);
        __labrptresultmapper.selectAs(LabItemDict::getIsCalcItem, LabRptresult::getIsCalcItem);
        __labrptresultmapper.selectAs("itmdict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
        __labrptresultmapper.leftJoin(LabItemDict.class, "itmdict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
        __labrptresultmapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());

        __labrptresultmapper.ge(LabRptresult::getSampleda, startTime);
        __labrptresultmapper.le(LabRptresult::getSampleda, endTime);
        __labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        __labrptresultmapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
        __labrptresultmapper.orderByAsc(LabRptresult::getDisplayOrder);

        List<LabRptresult> rptResults = labRptresultMapper.selectJoinList(LabRptresult.class, __labrptresultmapper);
        //
        // LabMaininfo finalMainInfoEntry = mainInfoEntry;

        /*【【【【【【【【【【-----------------------V0版本------------------------】】】】】】】】】】*/
        //Long st = System.currentTimeMillis();

        /*文字结果处理*/
        //CalcTextResult(finalMainInfoEntry, rptResults);
        //printLog(rptResults);
        /*结果二次处理*/
        //CalcTransResult(finalMainInfoEntry, rptResults);
        //printLog(rptResults);

        //计算项目处理
        //CalcFormulaItemResult(finalMainInfoEntry, rptResults);
        //printLog(rptResults);

        /*计算危急值*/
        //CalcItemDictCritical(finalMainInfoEntry, rptResults);
        //printLog(rptResults);

        /*计算结果标识特殊规则*/
        //CalcItemDictSpecialRules(finalMainInfoEntry, rptResults);

        //Long st2 = System.currentTimeMillis();

        //System.out.println("计算结果总共耗时：" + (st2 - st) + "ms");
        /*【【【【【【【【【【-----------------------------------------------】】】】】】】】】】*/

        /*【【【【【【【【【【-----------------------V1版本------------------------】】】】】】】】】】*/
        Long st = System.currentTimeMillis();
        /*查询报告项目备用*/
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, labMaininfo.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        //查询计算项目
        List<LabItemDict> items = itemList.stream().filter(p -> p.getIsCalcItem() == 1).collect(Collectors.toList());

        // //查询计算项目
        // LambdaQueryWrapper<LabItemDict> labitemdictQuery = new LambdaQueryWrapper<>();
        // labitemdictQuery.eq(LabItemDict::getRptGroup, labMaininfo.getRptGroup());
        // labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        // labitemdictQuery.eq(LabItemDict::getEnable, 1);
        // labitemdictQuery.eq(LabItemDict::getIsCalcItem, 1);
        // labitemdictQuery.orderByAsc(LabItemDict::getSeq);
        // List<LabItemDict> items = labItemDictMapper.selectList(labitemdictQuery);

        for (LabItemDict item : items) {
            String calcItemFormula = item.getCalcItemFormula();
            for (LabRptresult rptResult : rptresultArr) {
                if (calcItemFormula.contains(rptResult.getItemNo())) {


                    // 合并逻辑
                    //mergeData(item, rptResult);

                }
            }
        }


        // List<String> collect2 = items.stream().map(p -> p.getCalcItemFormula()).collect(Collectors.toList());
        //
        // //循环rptresultArr收集项目代号
        // List<String> itemNoList = rptresultArr.stream().map(p -> p.getItemNo()).collect(Collectors.toList());
        //
        // //循环items判断是否包含itemNoList
        // List<LabItemDict> collect = items.stream().filter(p -> itemNoList.contains(p.getItemNo())).collect(Collectors.toList());
        //
        // //判断items的CALC_ITEM_FORMULA里是否包含rptresultArr的itemNo
        // if (CollectionUtils.isNotEmpty(collect)) {
        //     //循环collect判断是否有CALC_ITEM_FORMULA里包含rptresultArr的itemNo
        //     List<LabItemDict> collect1 = collect.stream().filter(p -> p.getCalcItemFormula().contains(p.getItemNo())).collect(Collectors.toList());
        //     if (CollectionUtils.isNotEmpty(collect1)) {
        //         //循环collect1判断是否有CALC_ITEM_FORMULA里包含rptresultArr的itemNo
        //     }
        // }

        /*文字结果*/
        labRptresultCalcService.CalcTextResultV1(labMaininfo, rptresultArr, itemList);
        /*结果二次处理*/
        labRptresultCalcService.CalcTransResultV1(labMaininfo, rptresultArr, itemList);
        /*计算项目处理*/
        labRptresultCalcService.CalcFormulaItemResultV1(labMaininfo, rptresultArr, itemList);
        /*计算危急值*/
        labRptresultCalcService.CalcItemDictCriticalV1(labMaininfo, rptresultArr, itemList);
        /*计算结果标识特殊规则*/
        labRptresultCalcService.CalcItemDictSpecialRulesV1(labMaininfo, rptresultArr);

        /*计算完成 更新 结果*/
        this.saveOrUpdateBatch(rptresultArr);

        List<LabRptresult> alarmList = rptresultArr.stream().filter(p -> ToolsUtils.isNotEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(alarmList)) {
            labMaininfo.setIsAlarm(1);
            int ri = labMaininfoMapper.updateById(labMaininfo);
        } else {
            labMaininfo.setIsAlarm(0);
            int rii = labMaininfoMapper.updateById(labMaininfo);
        }
        Long st2 = System.currentTimeMillis();
        System.out.println("调优==========》计算结果总共耗时：" + (st2 - st) + "ms");
        /*【【【【【【【【【【----------------------------------------------------】】】】】】】】】】*/


        // String itmNo = labRptresult.getItemNo();
        // List<LabRptresult> rptresultList = rptResults.stream().filter(p -> p.getItemNo().equals(itmNo)).collect(Collectors.toList());
        // if (!BeanUtil.isEmpty(rptresultList) && !rptresultList.isEmpty()) {
        //     labRptresult = rptresultList.get(0);
        // }

        return Result.succ(1, "成功", labMaininfo);
    }

    @Override
    public Result removeLabRptResultList(RptResultDto resultDto) {
        List<LabRptresult> labRptresults = resultDto.getLabRptresults();
        //收集id
        List<String> ids = labRptresults.stream().map(LabRptresult::getId).collect(java.util.stream.Collectors.toList());
        int i = labRptresultMapper.deleteBatchIds(ids);
        if (i > 0) {
            return Result.succ(1, "成功", null);
        } else {
            return Result.fail("失败");
        }
    }


    @Override
    public void CalcItemDictSpecialRules(LabMaininfo mainInfo, List<LabRptresult> rptresultlist) {
        //判断报告单元结果中是否有特殊规则
        List<String> collect = rptresultlist.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            LambdaQueryWrapper<LabItemDictSpecialRules> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabItemDictSpecialRules::getRptGroup, mainInfo.getRptGroup()).eq(LabItemDictSpecialRules::getIsEnable, 1).eq(LabItemDictSpecialRules::getDelFlag, 0).in(LabItemDictSpecialRules::getItemNo, collect);
            List<LabItemDictSpecialRules> labItemDictSpecialRules = labItemDictSpecialRulesMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtils.isEmpty(labItemDictSpecialRules)) {
                return;
            }
            //循环规则列表，判断结果值是否满足，满足则更新结果标识
            labItemDictSpecialRules.forEach(a -> {
                try {
                    Optional<LabRptresult> first = rptresultlist.stream().filter(p -> p.getItemNo().equals(a.getItemNo())).findFirst();
                    if (first.isPresent()) {
                        LabRptresult labRptresult = first.get();
                        //套入sql判断是否满足公式结果
                        if (StrUtil.isNotEmpty(labRptresult.getTestResult())) {
                            String sql = "select count(1) as result from dual where 1=1 ";
                            String afterReplace = new CalcItemFormulaReplcae().ReplaceCondition(a.getFactor().toLowerCase(), mainInfo, labRptresult);
                            if (StrUtil.isNotEmpty(afterReplace)) {
                                sql += " and " + afterReplace;
                            }
                            try {
                                List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sql);
                                System.out.println(calcResult);
                                if (CollectionUtils.isNotEmpty(calcResult) && "1".equals(calcResult.get(0).get("result") + "")) {
                                    labRptresult.setResultFlag(a.getExceptionSymbol());
                                    labRptresult.setExceptionSymbol(a.getResultFlag());
                                    labRptresultMapper.updateById(labRptresult);
                                }
                            } catch (Exception e) {
                                System.out.println("处理特殊规则结果异常");
                            }
                        }
                    }
                } catch (Exception e) {
                    System.out.println("处理特殊规则结果异常");
                }
            });
        }
    }


    @Override
    public Result findRptResultItemByTemp(Params params) {
        Timestamp startTime = Timestamp.valueOf(params.getSampleDaStr() + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(params.getSampleDaStr() + " 23:59:59");
        //此处联合查询以模板内容为主
        MPJLambdaWrapper<LabTemplateDetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabRptresultQ.class);
        queryWrapper.selectAs(LabTemplateDetail::getItemNo, LabRptresultTempDto::getTempItemNo);
        queryWrapper.selectAs(LabTemplateDetail::getItemNa, LabRptresultTempDto::getTempItemNa);
        queryWrapper.selectAs(LabTemplateDetail::getIsAssTemplate, LabRptresultTempDto::getIsAssTemplate);
        queryWrapper.selectAs(LabTemplateDetail::getTypeCode, LabRptresultTempDto::getTypeCode);
        queryWrapper.selectAs(LabTemplateDetail::getTextHeight, LabRptresultTempDto::getTextHeight);
        queryWrapper.selectAs(LabTemplateDetail::getTypeFlag, LabRptresultTempDto::getTypeFlag);
        queryWrapper.selectAs(LabTemplateDetail::getSeq, LabRptresultTempDto::getDisplayOrder);
        queryWrapper.selectAs(LabTemplateDetail::getDetailGroup, LabRptresultTempDto::getDetailGroup);
        queryWrapper.selectAs(LabTemplateDetail::getDetailGroup2, LabRptresultTempDto::getDetailGroup2);
        queryWrapper.selectAs(LabTemplateDetail::getShowRowCol, LabRptresultTempDto::getShowRowCol);
        queryWrapper.selectAs(LabTemplateDetail::getTemplateId, LabRptresultTempDto::getTemplateId);
        queryWrapper.selectAs(LabTemplateDetail::getSeq, LabRptresultTempDto::getSeq);
        queryWrapper.selectAs(LabItemDict::getRef, LabRptresultTempDto::getRef);
        queryWrapper.selectAs(LabItemDict::getDefValue3, LabRptresultTempDto::getDefValue3);
        queryWrapper.selectAs(LabItemDict::getIsCalcItem, LabRptresultTempDto::getIsCalcItem);
        queryWrapper.selectAs(LabItemDict::getCalcItemFormula, LabRptresultTempDto::getCalcItemFormula);

        //根据ItemNo关联模板内容展示
        //fixme:为避免被格式化掉显示样式，后面需要将on改成外部初始化MPJLambdaWrapper<LabRptresultQ>
        queryWrapper.leftJoin(LabRptresultQ.class, on -> on.eq(LabRptresultQ::getItemNo, LabTemplateDetail::getItemNo)//阻止格式化
                .ge(LabRptresultQ::getSampleda, startTime)//阻止格式化
                .le(LabRptresultQ::getSampleda, endTime)//阻止格式化
                .eq(LabRptresultQ::getSampleNo, params.getSampleNo())//阻止格式化
                .eq(LabRptresultQ::getRptGroup, params.getRptGroup())//阻止格式化
                .eq(LabRptresultQ::getDelFlag, 0)//阻止格式化

        );
        queryWrapper.innerJoin(LabTemplate.class, p -> p.eq(LabTemplate::getRptGroup, params.getRptGroup())//阻止格式化
                .eq(LabTemplate::getId, LabTemplateDetail::getTemplateId)//阻止格式化
                .eq(LabTemplate::getIsAutoApply, 1)//阻止格式化
                .eq(LabTemplate::getDelFlag, 0));
        queryWrapper.innerJoin(LabItemDict.class, p -> p.eq(LabItemDict::getDelFlag, 0)//阻止格式化
                .eq(LabItemDict::getRptGroup, LabTemplate::getRptGroup)//阻止格式化
                .eq(LabItemDict::getItemNo, LabTemplateDetail::getItemNo));
        queryWrapper.eq(LabTemplateDetail::getDelFlag, 0);
        queryWrapper.orderByAsc(LabTemplateDetail::getSeq);
        queryWrapper.orderByAsc(LabTemplateDetail::getDetailGroup);
        queryWrapper.orderByAsc(LabTemplateDetail::getDetailGroup2);
        List<LabRptresultTempDto> labRptresultTempDtos = this.labTemplateDetailMapper.selectJoinList(LabRptresultTempDto.class, queryWrapper);
        if (labRptresultTempDtos.size() > 0) {
            return Result.succ(this.getRptresultloadText(labRptresultTempDtos));

        }
        return Result.fail("获取模板数据，请联系管理员！");
    }

    @Override
    public Result findRptResultItemByTempId(Params params) {
        List<LabRptresultTempDto> labRptresultTempDtos = getRptResults(params);
        return Result.succ(labRptresultTempDtos);
    }

    /**
     * 更换报告模板数据
     * 整体流程为：先查询出所有报告数据，并将所有数据软删除，再根据选择的模板ID生成新的结果数据
     **/
    @Override
    public Result upDataRptResultByTempId(Params params) {
        if (StringUtils.isEmpty(params.getMainInfoId())) {
            return Result.fail("请选选择检验信息");
        }

        //查询到所有maininfo下的所有检查结果并软删除
        List<LabRptresultTempDto> rptResults = this.getRptResultsByMainInfoId(params);
        //若选择的模板ID为空，results有数据，且返回数据关联模板的项目
        if (StringUtils.isEmpty(params.getTemplateId()) && rptResults.size() > 0) {
            LabRptresultTempDto labRptresultTempDto = rptResults.get(0);
            params.setTemplateId(labRptresultTempDto.getTemplateId());
            return Result.succ(getRptResults(params));
        }
        //若选择的模板ID不为空，results有数据，且模板ID和results数据模板ID则范围模板项目
        if (!StringUtils.isEmpty(params.getTemplateId()) && rptResults.size() > 0) {
            LabRptresultTempDto labRptresultTempDto = rptResults.get(0);
            //若选择的模板ID不为空，results有数据，且模板ID和results数据模板ID则范围模板项目
            if (labRptresultTempDto.getTemplateId().equals(params.getTemplateId())) {
                return Result.succ(getRptResults(params));
            } else {
                //否则删除旧的模板数据查询匹配的模板项目
                List<String> ids = rptResults.stream().map(LabRptresultTempDto::getId).collect(Collectors.toList());
                labRptresultMapper.deleteBatchIds(ids);
                return Result.succ(getRptResults(params));
            }
        }
        //若results表无数据，则直接返回默认模板项目
        return Result.succ(getRptResults(params));
    }


    @Override
    public Result findLabTemplateDetailByTempId(String templateId) {
        List<LabTextResultDto> labTextResults = getLabTextResults(templateId);
        return Result.succ(labTextResults);
    }

    private List<LabTextResultDto> getLabTextResults(String templateId) {
        MPJLambdaWrapper<LabTextResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabTextResult.class);
        queryWrapper.leftJoin(LabTemplateDetail.class, p -> //阻止格式化
                p.eq(LabTextResult::getItemNo, LabTemplateDetail::getItemNo));
        queryWrapper.eq(LabTextResult::getDelFlag, "0");
        queryWrapper.eq(LabTemplateDetail::getTemplateId, templateId);
        queryWrapper.orderByAsc(LabTextResult::getItemNo, LabTextResult::getSeq);
        List<LabTextResultDto> labTextResults = labTextResultMapper.selectJoinList(LabTextResultDto.class, queryWrapper);
        return labTextResults;
    }

    /**
     * 查询模板项目并更新到lab_rptresult
     **/
    private Result getResultUpdate(Params params) {
        List<LabRptresultTempDto> labRptresultTempDtos = getRptResults(params);
        saveOrUpdateLabRptresults(labRptresultTempDtos, params);
        return Result.succ(labRptresultTempDtos);
    }

    @Transactional
    List<LabRptresultTempDto> saveOrUpdateLabRptresults(List<LabRptresultTempDto> labRptresultTempDtos, Params params) {
        LambdaQueryWrapper<LabRptresult> lambdaQueryWrappers = new LambdaQueryWrapper<>();
        Timestamp sapmpleda = Timestamp.valueOf(params.getSampleDaStr() + " 00:00:00");
        labRptresultTempDtos.forEach(labRptresultTempDto -> {
            LabRptresult labRptresult = new LabRptresult();
            // 将 LabRptresultTempDto 的属性复制到 LabRptresult
            BeanUtils.copyProperties(labRptresultTempDto, labRptresult);
            labRptresult.setSampleda(sapmpleda);
            labRptresult.setRptGroup(params.getRptGroup());
            labRptresult.setInstrCode(params.getRptGroup());
            labRptresult.setItemNo(labRptresultTempDto.getTempItemNo());
            labRptresult.setItemNa(labRptresultTempDto.getTempItemNa());
            if (StringUtils.isEmpty(labRptresultTempDto.getMaininfoId())) {
                labRptresult.setMaininfoId(labRptresultTempDto.getMaininfoId());
            } else {
                labRptresult.setMaininfoId(params.getMainInfoId());
            }
            labRptresult.setDelFlag(0);
            lambdaQueryWrappers.eq(LabRptresult::getSampleNo, labRptresult.getSampleNo());
            lambdaQueryWrappers.eq(LabRptresult::getRptGroup, labRptresult.getRptGroup());
            lambdaQueryWrappers.eq(LabRptresult::getSampleda, sapmpleda);
            lambdaQueryWrappers.eq(LabRptresult::getItemNo, labRptresult.getItemNo());
            // 保存到数据库
            this.saveOrUpdate(labRptresult, lambdaQueryWrappers);
            labRptresultTempDto.setId(labRptresult.getId());
        });
        return labRptresultTempDtos;
    }

    private List<LabRptresultTempDto> getRptResults(Params params) {
        Timestamp sampleDa = Timestamp.valueOf(params.getSampleDaStr() + " 00:00:00");
        //此处联合查询以模板内容为主
        MPJLambdaWrapper<LabTemplateDetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabRptresultQ.class);
        queryWrapper.selectAs(LabTemplateDetail::getItemNo, LabRptresultTempDto::getTempItemNo);
        queryWrapper.selectAs(LabTemplateDetail::getItemNa, LabRptresultTempDto::getTempItemNa);
        queryWrapper.selectAs(LabTemplateDetail::getIsAssTemplate, LabRptresultTempDto::getIsAssTemplate);
        queryWrapper.selectAs(LabTemplateDetail::getTypeCode, LabRptresultTempDto::getTypeCode);
        queryWrapper.selectAs(LabTemplateDetail::getTextHeight, LabRptresultTempDto::getTextHeight);
        queryWrapper.selectAs(LabTemplateDetail::getTypeFlag, LabRptresultTempDto::getTypeFlag);
        queryWrapper.selectAs(LabTemplateDetail::getSeq, LabRptresultTempDto::getDisplayOrder);
        queryWrapper.selectAs(LabTemplateDetail::getDetailGroup, LabRptresultTempDto::getDetailGroup);
        queryWrapper.selectAs(LabTemplateDetail::getDetailGroup2, LabRptresultTempDto::getDetailGroup2);
        queryWrapper.selectAs(LabTemplateDetail::getShowRowCol, LabRptresultTempDto::getShowRowCol);
        queryWrapper.selectAs(LabTemplateDetail::getTemplateId, LabRptresultTempDto::getTemplateId);
        queryWrapper.selectAs(LabTemplateDetail::getSeq, LabRptresultTempDto::getSeq);
        queryWrapper.selectAs(LabItemDict::getRef, LabRptresultTempDto::getRef);
        queryWrapper.selectAs(LabItemDict::getDefValue3, LabRptresultTempDto::getDefValue3);
        queryWrapper.selectAs(LabItemDict::getIsCalcItem, LabRptresultTempDto::getIsCalcItem);
        queryWrapper.selectAs(LabItemDict::getCalcItemFormula, LabRptresultTempDto::getCalcItemFormula);

        //根据ItemNo关联模板内容展示
        //若MainInfoId不存在，则LabRptresultQ不根据MainInfoId过滤，否则根据MainInfoId过滤
        if (StringUtils.isEmpty(params.getMainInfoId())) {
            queryWrapper.leftJoin(LabRptresultQ.class, on -> on.eq(LabRptresultQ::getItemNo, LabTemplateDetail::getItemNo)//阻止格式化
                    .eq(LabRptresultQ::getSampleda, sampleDa)//阻止格式化
                    .eq(LabRptresultQ::getSampleNo, params.getSampleNo())//阻止格式化
                    .eq(LabRptresultQ::getRptGroup, params.getRptGroup())//阻止格式化
                    .eq(LabRptresultQ::getDelFlag, 0)//阻止格式化
            );
        } else {
            queryWrapper.leftJoin(LabRptresultQ.class, on -> on.eq(LabRptresultQ::getItemNo, LabTemplateDetail::getItemNo)//阻止格式化
                    .eq(LabRptresultQ::getSampleda, sampleDa)//阻止格式化
                    .eq(LabRptresultQ::getMaininfoId, params.getMainInfoId())//阻止格式化
                    .eq(LabRptresultQ::getSampleNo, params.getSampleNo())//阻止格式化
                    .eq(LabRptresultQ::getRptGroup, params.getRptGroup())//阻止格式化
                    .eq(LabRptresultQ::getDelFlag, 0)//阻止格式化

            );
        }
        //如果templateId不存在，则LabTemplate不根据templateId过滤，否则根据templateId过滤
        if (StringUtils.isEmpty(params.getTemplateId())) {
            queryWrapper.innerJoin(LabTemplate.class, p -> p.eq(LabTemplate::getRptGroup, params.getRptGroup())//阻止格式化
                    .eq(LabTemplate::getId, LabTemplateDetail::getTemplateId)//阻止格式化
                    .eq(LabTemplate::getIsAutoApply, 1)//自主选择模板关闭默认过滤
                    .eq(LabTemplate::getDelFlag, 0));//阻止格式化
        } else {
            queryWrapper.innerJoin(LabTemplate.class, p -> p.eq(LabTemplate::getRptGroup, params.getRptGroup())//阻止格式化
                    .eq(LabTemplate::getId, LabTemplateDetail::getTemplateId)//阻止格式化
                    //.eq(LabTemplate::getIsAutoApply,1)//自主选择模板关闭默认过滤
                    .eq(LabTemplate::getDelFlag, 0));
            queryWrapper.eq(LabTemplateDetail::getTemplateId, params.getTemplateId());
        }
        queryWrapper.innerJoin(LabItemDict.class, p -> p.eq(LabItemDict::getDelFlag, 0)//阻止格式化
                .eq(LabItemDict::getRptGroup, LabTemplate::getRptGroup)//阻止格式化
                .eq(LabItemDict::getItemNo, LabTemplateDetail::getItemNo));
        queryWrapper.eq(LabTemplateDetail::getDelFlag, 0);
        queryWrapper.orderByAsc(LabTemplateDetail::getSeq);
        queryWrapper.orderByAsc(LabTemplateDetail::getDetailGroup);
        queryWrapper.orderByAsc(LabTemplateDetail::getDetailGroup2);
        List<LabRptresultTempDto> labRptresultTempDtos = this.labTemplateDetailMapper.selectJoinList(LabRptresultTempDto.class, queryWrapper);
        return getRptresultloadText(labRptresultTempDtos);
    }

    //将项目文本结果，适配到图文报表项目中
    private List<LabRptresultTempDto> getRptresultloadText(List<LabRptresultTempDto> labRptresultTempDtos) {
        List<LabTextResultDto> labTextResults = this.getLabTextResults(labRptresultTempDtos.get(0).getTemplateId());
        //遍历labRptresultTempDtos，将labTextResults中itemNo相同的数据补充到textResults字段中
        labRptresultTempDtos.forEach(a -> {
            List<LabTextResultDto> textResultDtos = new ArrayList<>();
            for (LabTextResultDto labTextResult : labTextResults) {
                //确认选择是这这个值，则设置checked为true
                if (labTextResult.getItemNo().equals(a.getTempItemNo())) {
                    labTextResult.setChecked(false);
                    if (!StringUtils.isEmpty(a.getResultDesc())) {
                        List<String> itemIds = Arrays.asList(a.getResultDesc().split(","));
                        //判断labTextResult ID是否在结果值中，若在则checked为true
                        if (itemIds.contains(labTextResult.getId())) {
                            labTextResult.setChecked(true);
                        }
                    }
                    textResultDtos.add(labTextResult);
                }
            }
            a.setTextResults(textResultDtos);
            a.setChecked(false);
            if (!StringUtils.isEmpty(a.getTestResult()) && a.getTestResult().equals("isChecked")) {
                a.setChecked(true);
            }
        });
        return labRptresultTempDtos;
    }

    //仅用于获取图文报告已保存项目进行判断不做展示
    private List<LabRptresultTempDto> getRptResultsByMainInfoId(Params params) {
        Timestamp startTime = Timestamp.valueOf(params.getSampleDaStr() + " 00:00:00");
        //此处联合查询以模板内容为主
        MPJLambdaWrapper<LabRptresultQ> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabRptresultQ.class);
        queryWrapper.selectAs(LabTemplateDetail::getItemNo, LabRptresultTempDto::getTempItemNo);
        queryWrapper.selectAs(LabTemplateDetail::getItemNa, LabRptresultTempDto::getTempItemNa);
        queryWrapper.selectAs(LabTemplateDetail::getIsAssTemplate, LabRptresultTempDto::getIsAssTemplate);
        queryWrapper.selectAs(LabTemplateDetail::getTypeCode, LabRptresultTempDto::getTypeCode);
        queryWrapper.selectAs(LabTemplateDetail::getTextHeight, LabRptresultTempDto::getTextHeight);
        queryWrapper.selectAs(LabTemplateDetail::getTypeFlag, LabRptresultTempDto::getTypeFlag);
        queryWrapper.selectAs(LabTemplateDetail::getSeq, LabRptresultTempDto::getDisplayOrder);
        queryWrapper.selectAs(LabTemplateDetail::getDetailGroup, LabRptresultTempDto::getDetailGroup);
        queryWrapper.selectAs(LabTemplateDetail::getDetailGroup2, LabRptresultTempDto::getDetailGroup2);
        queryWrapper.selectAs(LabTemplateDetail::getShowRowCol, LabRptresultTempDto::getShowRowCol);
        queryWrapper.selectAs(LabTemplateDetail::getTemplateId, LabRptresultTempDto::getTemplateId);
        queryWrapper.selectAs(LabTemplateDetail::getSeq, LabRptresultTempDto::getSeq);
        queryWrapper.selectAs(LabTemplateDetail::getTemplateId, LabRptresultTempDto::getTemplateId);
        queryWrapper.selectAs(LabItemDict::getRef, LabRptresultTempDto::getRef);
        queryWrapper.selectAs(LabItemDict::getDefValue3, LabRptresultTempDto::getDefValue3);
        queryWrapper.selectAs(LabItemDict::getIsCalcItem, LabRptresultTempDto::getIsCalcItem);
        queryWrapper.selectAs(LabItemDict::getCalcItemFormula, LabRptresultTempDto::getCalcItemFormula);

        //根据ItemNo关联模板内容展示
        queryWrapper.leftJoin(LabTemplateDetail.class, on -> on.eq(LabTemplateDetail::getItemNo, LabRptresultQ::getItemNo)//阻止格式化
                .eq(LabTemplateDetail::getDelFlag, 0));
        queryWrapper.innerJoin(LabTemplate.class, p -> p.eq(LabTemplate::getRptGroup, params.getRptGroup())//阻止格式化
                .eq(LabTemplate::getId, LabTemplateDetail::getTemplateId)//阻止格式化
//                        .eq(LabTemplate::getIsAutoApply,1)
                .eq(LabTemplate::getDelFlag, 0));
        queryWrapper.innerJoin(LabItemDict.class, p -> p.eq(LabItemDict::getDelFlag, 0)//阻止格式化
                .eq(LabItemDict::getRptGroup, LabTemplate::getRptGroup)//阻止格式化
                .eq(LabItemDict::getItemNo, LabTemplateDetail::getItemNo));//阻止格式化
        queryWrapper.eq(LabRptresultQ::getSampleda, startTime);
        queryWrapper.eq(LabRptresultQ::getSampleNo, params.getSampleNo());
        queryWrapper.eq(LabRptresultQ::getRptGroup, params.getRptGroup());
        queryWrapper.eq(LabRptresultQ::getDelFlag, 0);

        if (!StringUtils.isEmpty(params.getTemplateId())) {
            queryWrapper.eq(LabTemplateDetail::getTemplateId, params.getTemplateId());
        }
        queryWrapper.orderByAsc(LabTemplateDetail::getSeq);
        queryWrapper.orderByAsc(LabTemplateDetail::getDetailGroup);
        queryWrapper.orderByAsc(LabTemplateDetail::getDetailGroup2);
        return this.labRptresultQMapper.selectJoinList(LabRptresultTempDto.class, queryWrapper);
    }

    public void printLog(List<LabRptresult> rptResults) {
        System.out.println("=======================================");
        rptResults.forEach(a -> {
            System.out.println("参考范围:" + a.getTestResult() + "," + a.getItemNa() + "#############" + a.getTestResult() + "^^^^^^^^^^^^^^" + a.getResultFlag() + "$$$$$$$$$$$$" + a.getIsAlarm());
        });
        System.out.println("=======================================");
    }

    @Override
    public Result deleteRptResults(DeleteResultParam deleteResultParam) {
        SysUser sysUser = RedisUserManager.getUser();
        List<LabRptresult> labRptResultList = deleteResultParam.getLabRptResultList();
        List<String> ids = labRptResultList.stream().map(LabRptresult::getId).collect(Collectors.toList());
        List<LabResultAmendment> labResultAmendments = new ArrayList<>();
        for (LabRptresult rptresult : labRptResultList) {
            LabResultAmendment labResultAmendment = new LabResultAmendment();
            labResultAmendment.setMaininfoId(rptresult.getMaininfoId());
            labResultAmendment.setWlResult(rptresult.getId());
            labResultAmendment.setItemNa(rptresult.getItemNa());
            labResultAmendment.setItemNo(rptresult.getItemNo());
            labResultAmendment.setOriginalResult(rptresult.getTestResult());
            labResultAmendment.setAmendedResult("删除结果");
            labResultAmendment.setAmendedDate(new Timestamp(new Date().getTime()));
            labResultAmendment.setAmendedUserId(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getId() : "");
            labResultAmendment.setAmendedUserName(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getRealname() : "");
            labResultAmendments.add(labResultAmendment);
        }
        labResultAmendmentService.saveBatch(labResultAmendments);
        int i = labRptresultMapper.deleteBatchIds(ids);
        if (i > 0) {
            return Result.succ(1, "删除报告项目成功", "");
        } else {
            AtomicInteger delete = new AtomicInteger();
            //模板沒有id的情況 根据标本号删除
            labRptResultList.forEach(a -> {
                LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabRptresult::getRptGroup, a.getRptGroup()).eq(LabRptresult::getSampleda, a.getSampleda()).eq(LabRptresult::getSampleNo, a.getSampleNo()).eq(LabRptresult::getItemNo, a.getItemNo());
                delete.set(labRptresultMapper.delete(lambdaQueryWrapper));
            });
            if (delete.get() > 0) {
                return Result.succ(1, "删除报告项目成功", "");
            }
            return Result.fail("删除报告项目失败");
        }
    }

    @Override
    public Result updateRptResult(LabRptresult labRptresult) throws JsonProcessingException {
        return insertRptResult(labRptresult);
    }

    @Override
    public Result updateRepetition(LabRptresult labRptresult) {
        LambdaUpdateWrapper<LabRptresult> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(LabRptresult::getResultFlag, "M");
        wrapper.set(LabRptresult::getIsAlarm, 0);
        wrapper.set(LabRptresult::getAlarmText, null);
        wrapper.set(LabRptresult::getAlarmType, null);
        wrapper.set(LabRptresult::getCatchColor, null);
        wrapper.set(LabRptresult::getColorFor, "0");
        wrapper.eq(LabRptresult::getId, labRptresult.getId());
        int i = labRptresultMapper.update(labRptresult, wrapper);

        if (i > 0) {
            return Result.succ(1, "修改报告项目成功", "");
        } else {
            return Result.fail("修改报告项目失败");
        }
    }


    @Override
    public Result findRptResultItem(Params params) {
        if (StringUtils.isEmpty(params.getRptGroup())) {
            return Result.fail("报告单元不允许为空");
        }
        LambdaQueryWrapper<LabItemDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabItemDict::getDelFlag, 0).eq(LabItemDict::getEnable, 1).eq(LabItemDict::getRptGroup, params.getRptGroup());
        if (StrUtil.isNotEmpty(params.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNo, params.getSearchValue()).or().like(LabItemDict::getItemNa, params.getSearchValue()));
        }
        queryWrapper.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> labItemDicts = labItemDictMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", labItemDicts);
    }

    @Override
    public Result findRptResultItemAll(Params params) {
        LambdaQueryWrapper<LabItemDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabItemDict::getDelFlag, 0).eq(!StringUtils.isEmpty(params.getRptGroup()), LabItemDict::getRptGroup, params.getRptGroup());
        if (StrUtil.isNotEmpty(params.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNo, params.getSearchValue()).or().like(LabItemDict::getItemNa, params.getSearchValue()));
        }
        List<LabItemDict> labItemDicts = labItemDictMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", labItemDicts);
    }


    @Override
    public Result findReviewedResutBySampleNo(String maininfoId) {
        LambdaQueryWrapper<LabRptresult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptresult::getDelFlag, 0);
        queryWrapper.eq(LabRptresult::getMaininfoId, maininfoId);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(queryWrapper);
        //工作组/下部分筛选条件需求不明确
        return Result.succ(1, "查询成功", labRptresults);
    }

    @Override
    public Result batchAddResultItemList(RptResultDto dto) {
        try {
            List<LabRptresult> labRptresults = dto.getLabRptresults();
            for (LabRptresult labRptresult : labRptresults){
                LambdaQueryWrapper<LabRptresult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LabRptresult::getSampleda, labRptresult.getSampleda())
                        .eq(LabRptresult::getRptGroup, labRptresult.getRptGroup())
                        .eq(LabRptresult::getSampleNo, labRptresult.getSampleNo())
                        .eq(LabRptresult::getItemNo, labRptresult.getItemNo())
                        .eq(LabRptresult::getDelFlag,0);
                this.saveOrUpdate(labRptresult, queryWrapper);
            }
            return Result.succ(1, "添加成功", null);
        }catch (Exception e){
            return Result.fail(e.getMessage());
        }


        // boolean b = this.saveOrUpdateBatch(labRptresults);
        // if (b) {
        //     return Result.succ(1, "添加成功", null);
        // } else {
        //     return Result.fail(400, "添加失败", "");
        // }
    }


    /**
     * 重新计算检验结果
     */
    @Override
    public Result reCalcRptRssults(LabMaininfo mainInfo) {
        if (BeanUtil.isEmpty(mainInfo)) {
            return Result.succ("成功");
        }
        if (!BeanUtil.isEmpty(mainInfo.getIsChk()) && mainInfo.getIsChk().compareTo(new BigDecimal(0)) > 0) {
            return Result.fail("当前标本已审核,不允许再次新增/修改结果!");
        }
        LambdaQueryWrapper<LabRptresult> labrptresultmapper = new LambdaQueryWrapper<>();
        Timestamp timestamp = new Timestamp(mainInfo.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        labrptresultmapper.ge(LabRptresult::getSampleda, startTime);
        labrptresultmapper.le(LabRptresult::getSampleda, endTime);
        labrptresultmapper.eq(LabRptresult::getRptGroup, mainInfo.getRptGroup());
        labrptresultmapper.eq(LabRptresult::getSampleNo, mainInfo.getSampleNo());
        labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> rptResults = labRptresultMapper.selectList(labrptresultmapper);

        if (CollectionUtils.isNotEmpty(rptResults)) {
            ////根据申请编码 找到申请项目明细
            //找出fee_code为空得数据
            List<LabRptresult> newRptReusltList = rptResults.stream().filter(p -> org.apache.commons.lang3.StringUtils.isBlank(p.getFeeCode())).collect(Collectors.toList());
            if (ToolsUtils.isNotEmpty(newRptReusltList)) {
                MPJLambdaWrapper<LabRptresult> queryWrapper1 = new MPJLambdaWrapper<>();
                queryWrapper1.selectAll(LabRptresult.class);
                queryWrapper1.selectAs("rd", LabReqdetail::getFeeCode, LabRptresult::getFeeCode);
                queryWrapper1.selectAs("rd", LabReqdetail::getFeeName, LabRptresult::getFeeName);
                //.leftJoin(LabItemDict.class, "di", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0))
                queryWrapper1.leftJoin(LabFeeitemVsItemDict.class, "vs", p -> p.eq(LabFeeitemVsItemDict::getRptGroup, LabItemDict::getRptGroup).eq(LabFeeitemVsItemDict::getItemNo, LabItemDict::getItemNo).eq(LabFeeitemVsItemDict::getDelFlag, 0));
                queryWrapper1.leftJoin(LabFeeItem.class, "fe", p -> p.eq(LabFeeItem::getFeeCode, LabFeeitemVsItemDict::getFeeCode).eq(LabFeeItem::getDelFlag, 0));
                queryWrapper1.innerJoin(LabReqdetail.class, "rd", p -> p.eq(LabReqdetail::getFeeCode, LabFeeItem::getFeeCode).eq(LabReqdetail::getDelFlag, 0).eq(LabReqdetail::getReqNo, mainInfo.getReqNo()));
                queryWrapper1.in(LabRptresult::getId, newRptReusltList.stream().map(LabRptresult::getId).collect(Collectors.toList()));

                List<LabRptresult> feeRptresultList = labRptresultMapper.selectList(queryWrapper1);
                if (ToolsUtils.isNotEmpty(feeRptresultList)) {
                    List<LabRptresult> upRptReusltList = new ArrayList<>();
                    for (LabRptresult feeRptReuslt : feeRptresultList) {
                        LabRptresult upRptReuslt = new LabRptresult();
                        upRptReuslt.setId(feeRptReuslt.getId());
                        upRptReuslt.setSampleda(feeRptReuslt.getSampleda());
                        upRptReuslt.setFeeCode(feeRptReuslt.getFeeCode());
                        upRptReuslt.setFeeName(feeRptReuslt.getFeeName());
                        upRptReusltList.add(upRptReuslt);
                    }
                    this.updateBatchById(upRptReusltList);
                }
            }

            /*-----------------------------------------------*/
            //Long st1 = System.currentTimeMillis();
            /*文字结果处理*/
            //CalcTextResult(mainInfo, rptResults);
            //printLog(rptResults);
            /*结果二次处理*/
            //CalcTransResult(mainInfo, rptResults);
            //printLog(rptResults);
            //计算项目处理
            //CalcFormulaItemResult(mainInfo, rptResults);
            //printLog(rptResults);
            /*计算危急值*/
            //CalcItemDictCritical(mainInfo, rptResults);
            //printLog(rptResults);
            /*计算结果标识特殊规则*/
            //CalcItemDictSpecialRules(mainInfo, rptResults);
            //Long st2 = System.currentTimeMillis();
            //System.out.println("计算结果标识总共耗时：" + (st2 - st1) + "ms");
            /*-----------------------------------------------*/


            /*【【【【【【【【【【-----------------------V1版本------------------------】】】】】】】】】】*/
            Long st = System.currentTimeMillis();
            /*查询报告项目备用*/
            LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
            _labitemdictQuery.eq(LabItemDict::getRptGroup, mainInfo.getRptGroup());
            _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
            _labitemdictQuery.eq(LabItemDict::getEnable, 1);
            _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
            List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

            /*文字结果*/
            labRptresultCalcService.CalcTextResultV1(mainInfo, rptResults, itemList);
            /*结果二次处理*/
            labRptresultCalcService.CalcTransResultV1(mainInfo, rptResults, itemList);
            /*计算项目处理*/
            labRptresultCalcService.CalcFormulaItemResultV1(mainInfo, rptResults, itemList);
            /*计算危急值*/
            labRptresultCalcService.CalcItemDictCriticalV1(mainInfo, rptResults, itemList);
            /*计算结果标识特殊规则*/
            labRptresultCalcService.CalcItemDictSpecialRulesV1(mainInfo, rptResults);

            /*计算完成 更新 结果*/
            this.saveOrUpdateBatch(rptResults);
            //如果finalLabMaininfo下得所有rptResults得isResult为1，则finalLabMaininfo得isResult为1
            List<LabRptresult> _lst = rptResults.stream().filter(p -> (ToolsUtils.isEmpty(p.getIsResult()) || p.getIsResult() == 0)).collect(Collectors.toList());
            if (ToolsUtils.isEmpty(_lst)) {
                mainInfo.setIsResult(1);
            } else {
                mainInfo.setIsResult(0);
            }

            List<LabRptresult> alarmList = rptResults.stream().filter(p -> ToolsUtils.isNotEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(alarmList)) {
                mainInfo.setIsAlarm(1);
                int ri = labMaininfoMapper.updateById(mainInfo);
            } else {
                mainInfo.setIsAlarm(0);
                int rii = labMaininfoMapper.updateById(mainInfo);
            }
            Long st2 = System.currentTimeMillis();
            System.out.println("调优==========》重新计算结果总共耗时：" + (st2 - st) + "ms");
            /*【【【【【【【【【【----------------------------------------------------】】】】】】】】】】*/


        }
        return Result.succ("成功");
    }

    /**
     * 批量重新计算检验结果
     *
     * @param mainInfos 检验主记录集合
     */
    @Override
    public boolean reCalcRptRssultsMany(List<LabMaininfo> mainInfos) {
        if (BeanUtil.isEmpty(mainInfos.isEmpty())) {
            return true;
        }
        try {
            List<LabMaininfo> chkCounts = mainInfos.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk())).filter(p -> p.getIsChk().compareTo(new BigDecimal(0)) > 0).collect(Collectors.toList());
            if (!chkCounts.isEmpty()) {
                throw new Exception("存在已审核的数据");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        List<String> miIds = mainInfos.stream().map(LabMaininfo::getId).collect(Collectors.toList());
        LambdaQueryWrapper<LabRptresult> labrptresultmapper = new LambdaQueryWrapper<>();
        labrptresultmapper.in(LabRptresult::getMaininfoId, miIds);
        labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> rptResults = labRptresultMapper.selectList(labrptresultmapper);
        for (LabRptresult item : rptResults) {
            try {
                insertRptResult(item);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
        return true;
    }

    /**
     * 计算计算项目的值
     */
    @Override
    public Result CalcFormulaItemResult(LabMaininfo mainInfo, List<LabRptresult> rptresultlist) {
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, mainInfo.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getIsCalcItem, 1);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);

        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        try {
            for (LabItemDict item : itemList) {
                String formula = item.getCalcItemFormula();
                if (StringUtils.isEmpty(formula)) {
                    continue;
                }

                //----------------------------------------------公式计算
                Pattern pattern = Pattern.compile("(?i)(?<=\\[)[^\\[]*(?=\\])");
                Matcher matcher = pattern.matcher(formula);

                List<Result> currentResultList = new ArrayList<>();
                // Add relevant Result objects to currentResultList
                boolean isBreak = false;
                while (matcher.find()) {
                    String matchColMatchValue = matcher.group();

                    String matchResult = "";
                    for (LabRptresult result : rptresultlist) {
                        if (result.getItemNo().equals(matchColMatchValue)) {
                            matchResult = result.getTestResult();
                            break;
                        }
                    }

                    if (StringUtils.isEmpty(matchResult)) {
                        isBreak = true;
                        break;
                    }
                    try {
                        matchResult = new BigDecimal(matchResult).setScale(2, RoundingMode.HALF_UP).toString();
                    } catch (Exception e) {

                    }

                    formula = formula.replace("[" + matchColMatchValue + "]", matchResult);
                    //----------------------------------------------
                }
                if (!isBreak) {
                    formula = new CalcItemFormulaReplcae().ReplaceCondition(formula, mainInfo, null);
                    String ResValue = "";
                    try {
                        String sql = String.format("select " + formula + " as RESULT from dual ");
                        try {
                            List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sql);
                            // 遍历 List 中的每个 Map
                            for (Map<String, Object> map : calcResult) {
                                System.out.println(map);
                                ResValue = map.get("RESULT").toString();
                            }

                        } catch (Exception e) {
                            ResValue = "0.00";
                        }
                    } catch (Exception exception) {
                        //TODO
                        exception.printStackTrace();
                    }

                    //保留小数位数
                    String DecPos = item.getDecPos();
                    Integer _decPos = 0;
                    switch (DecPos) {
                        case "1":
                            _decPos = 1;
                            break;
                        case "2":
                            _decPos = 2;
                            break;
                        case "3":
                            _decPos = 3;
                            break;
                        case "4":
                            _decPos = 4;
                            break;
                        case "5":
                            _decPos = 5;
                            break;
                        case "6":
                            _decPos = 6;
                            break;
                    }
                    //检查结果中是否已经存在该计算项目
                    boolean isExist = false;
                    for (LabRptresult _item : rptresultlist) {
                        if (_item.getItemNo().equals(item.getItemNo())) {
                            _item.setTestResult(ResValue);
                            _item.setDisplayOrder(item.getSeq().toString());
                            _item.setRef(item.getRef());
                            _item.setItemDictId(item.getId());
                            //保留小数位数
                            if (item.getItemKind().equals("1")) {
                                BigDecimal decimalNumber = new BigDecimal(ResValue);
                                decimalNumber = decimalNumber.setScale(_decPos, BigDecimal.ROUND_HALF_UP); // 设置小数位数并进行四舍五入
                                _item.setTestResult(decimalNumber.toString());
                            }
                            _item.setIsResult(1);
                            int i = labRptresultMapper.updateById(_item);
                            if (i <= 0) {
                                return Result.fail("更新计算项目结果失败");
                            }
                            isExist = true;
                            break;
                        }
                    }
                    //如果不存在，则新增该计算项目
                    if (!isExist) {
                        LabRptresult newCalcItemResult = new LabRptresult();
                        BeanUtil.copyProperties(rptresultlist.get(0), newCalcItemResult, "id", "isAlarm", "alarmText", "rawData", "sco", "ct", "od", "cutoff", "resultFlag", "resultTimeStr", "ref", "resultDesc", "remark1", "remark2", "remark3", "remark4", "itemDictId", "feeCode", "feeName", "intResultId", "instrNa", "instrId", "adjustResult");
                        newCalcItemResult.setTestResult(ResValue);
                        //保留小数位数
                        if (item.getItemKind().equals("1")) {
                            BigDecimal decimalNumber = new BigDecimal(ResValue);
                            decimalNumber = decimalNumber.setScale(_decPos, BigDecimal.ROUND_HALF_UP); // 设置小数位数并进行四舍五入
                            newCalcItemResult.setTestResult(decimalNumber.toString());
                        }

                        /*处理结果中的申请项目,因为扫码上机时能带出对照的项目  即使是  计算项目*/

                        newCalcItemResult.setDisplayOrder(item.getSeq().toString());
                        newCalcItemResult.setItemNo(item.getItemNo());
                        newCalcItemResult.setItemNa(item.getItemNa());
                        newCalcItemResult.setRef(item.getRef());
                        newCalcItemResult.setItemDictId(item.getId());
                        int i = labRptresultMapper.insert(newCalcItemResult);
                        if (i <= 0) {
                            return Result.fail("插入计算项目失败");
                        } else {
                            rptresultlist.add(newCalcItemResult);
                        }
                    }
                }

            }
            CalcItemDictRefers(mainInfo, rptresultlist);
            return Result.succ("计算成功");
        } catch (Exception exception) {
            //TODO
            exception.printStackTrace();
        }

        return Result.fail("计算失败");
    }

    /**
     * 计算参考范围
     */
    @Override
    public void CalcItemDictRefers(LabMaininfo mainInfo, List<LabRptresult> rptresultlist) {
        MPJLambdaWrapper<LabItemDictRefer> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabItemDictRefer::getDelFlag, "0");
        queryWrapper.eq(LabItemDictRefer::getIsEnable, "1");
        queryWrapper.eq(LabItemDictRefer::getRptGroup, mainInfo.getRptGroup());
        List<String> itemNos = rptresultlist.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());

        if (!itemNos.isEmpty()) {
            queryWrapper.in(LabItemDictRefer::getItemNo, itemNos);
        } else {
            queryWrapper.eq(LabItemDictRefer::getOrgId, "-123!@#");
        }
        queryWrapper.orderByAsc(LabItemDictRefer::getSeq);
        List<LabItemDictRefer> LabItemDictRefers = labItemDictReferMapper.selectList(queryWrapper);

        /*
         *查询报告项目备用
         * */
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, mainInfo.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);

        if (!itemNos.isEmpty()) {
            _labitemdictQuery.in(LabItemDict::getItemNo, itemNos);
        } else {
            _labitemdictQuery.eq(LabItemDict::getItemNo, "-123!@#");
        }

        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        /*
         * 开始循环计算每一项的参考范围
         * */
        try {
            try {
                ExecutorService executorService = Executors.newFixedThreadPool(rptresultlist.size()); // 创建一个线程池
                CountDownLatch countDownLatch = new CountDownLatch(rptresultlist.size());

                for (LabRptresult item : rptresultlist) {
                    Future<?> future = executorService.submit(() -> {
                        //报告项目
                        try {
                            List<LabItemDict> itmLst = itemList.stream().filter(p -> p.getItemNo().equals(item.getItemNo()) && p.getRptGroup().equals(item.getRptGroup())).collect(Collectors.toList());
                            LabItemDict itemDict = null;
                            if (!itmLst.isEmpty()) {
                                itemDict = itmLst.get(0);
                            }

                            if (BeanUtil.isEmpty(itemDict)) {
                                return;
                            }

                            //先带出参考范围
                            item.setRef(StringUtils.isEmpty(itemDict.getRef()) ? "" : itemDict.getRef());
                            try {
                                if (!StringUtils.isEmpty(itemDict.getRef())) {
                                    /*解决青岛优抚  结果+3  变为3的BUG */
                                    if (ToolsUtils.isNotEmpty(itemDict.getItemKind()) && "1".equals(itemDict.getItemKind())) {
                                        BigDecimal decimalNumber = new BigDecimal(item.getTestResult());
                                        item.setResultFlag("M");
                                    }
                                }
                            } catch (Exception e) {
                                System.out.println("结果转换bigdecimal异常！");
                            }
                            //保留小数位数
                            String DecPos = itemDict.getDecPos();
                            Integer _decPos = 0;
                            switch (DecPos) {
                                case "1":
                                    _decPos = 1;
                                    break;
                                case "2":
                                    _decPos = 2;
                                    break;
                                case "3":
                                    _decPos = 3;
                                    break;
                                case "4":
                                    _decPos = 4;
                                    break;
                                case "5":
                                    _decPos = 5;
                                    break;
                                case "6":
                                    _decPos = 6;
                                    break;
                            }
                            boolean isDetailRef = false;
                            String refStr = itemDict.getRef();
                            try {
                                BigDecimal decimalNumber1 = new BigDecimal(item.getTestResult());
                                decimalNumber1 = decimalNumber1.setScale(_decPos, BigDecimal.ROUND_HALF_UP); // 设置小数位数并进行四舍五入
                                /*解决青岛优抚  结果+3  变为3的BUG */
                                if (ToolsUtils.isNotEmpty(itemDict.getItemKind()) && "1".equals(itemDict.getItemKind())) {
                                    item.setTestResult(decimalNumber1.toString());
                                }
                            } catch (Exception e) {
                                System.out.println("结果转换bigdecimal异常！");
                            }
                            List<LabItemDictRefer> _lst = LabItemDictRefers.stream().filter(p -> p.getRptGroup().equals(item.getRptGroup()) && p.getItemNo().equals(item.getItemNo())).collect(Collectors.toList());
                            for (LabItemDictRefer _itmRefer : _lst) {
                                boolean isFactorTrue = false;/*是否已有满足的条件*/
                                //没有条件
                                if (StringUtils.isEmpty(_itmRefer.getFactor())) {
                                    if (itemDict.getItemKind().equals("1")) {
                                        //检测结果
                                        if (!StringUtils.isEmpty(item.getTestResult())) {
                                            try {
                                                BigDecimal decimalNumber = new BigDecimal(item.getTestResult());
                                                decimalNumber = decimalNumber.setScale(_decPos, BigDecimal.ROUND_HALF_UP); // 设置小数位数并进行四舍五入
                                                item.setTestResult(decimalNumber.toString());
                                                //下限
                                                BigDecimal xxValue = new BigDecimal(_itmRefer.getLowerLimit());
                                                //上限
                                                BigDecimal sxValue = new BigDecimal(_itmRefer.getUpperLimit());

                                                if (decimalNumber.compareTo(xxValue) < 0) {
                                                    item.setResultFlag("L");
                                                    isDetailRef = true;
                                                    isFactorTrue = true;
                                                }
                                                if (decimalNumber.compareTo(sxValue) > 0) {
                                                    item.setResultFlag("H");
                                                    isDetailRef = true;
                                                    isFactorTrue = true;
                                                }
                                                if (decimalNumber.compareTo(xxValue) >= 0 && decimalNumber.compareTo(sxValue) <= 0) {
                                                    item.setResultFlag("M");
                                                    isDetailRef = true;
                                                    isFactorTrue = true;
                                                }
                                            } catch (Exception e) {
                                                System.out.println("转换结果异常！");
                                            }
                                        }
                                        refStr = _itmRefer.getRange();
                                    }

                                    if (isFactorTrue) {
                                        break;
                                    }
                                    continue;
                                }

                                String sql = "select count(1) as result from dual where 1=1 ";
                                String afterReplace = new CalcItemFormulaReplcae().ReplaceCondition(_itmRefer.getFactor().toLowerCase(), mainInfo, null);
                                if (StringUtils.isEmpty(afterReplace)) {
                                    //sql += " and 1=2 ";
                                } else {
                                    //处理扫码上机视图过来的数据是汉字的情况,反向映射
                                    afterReplace = afterReplace.replaceAll("男", "1").replaceAll("女", "2").replaceAll("未知", "3");
                                    sql += " and " + afterReplace;
                                }
                                try {
                                    List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sql);
                                    // 遍历 List 中的每个 Map
                                    String ResValue = "";
                                    for (Map<String, Object> map : calcResult) {
                                        // 遍历 Map 中的键值对
                                        for (Map.Entry<String, Object> entry : map.entrySet()) {
                                            String key = entry.getKey();
                                            Object value = entry.getValue();
                                            ResValue = value.toString();
                                        }
                                    }
                                    if (!StringUtils.isEmpty(ResValue) && ResValue.equals("1")) {
                                        if (itemDict.getItemKind().equals("1")) {
//                                if (BeanUtil.isEmpty(item.getTestResult())) {
//                                    continue;
//                                }
                                            //检测结果
                                            if (!StringUtils.isEmpty(item.getTestResult())) {
                                                try {
                                                    BigDecimal decimalNumber = new BigDecimal(item.getTestResult());
                                                    decimalNumber = decimalNumber.setScale(_decPos, BigDecimal.ROUND_HALF_UP); // 设置小数位数并进行四舍五入
                                                    item.setTestResult(decimalNumber.toString());
                                                    //下限
                                                    BigDecimal xxValue = new BigDecimal(_itmRefer.getLowerLimit());
                                                    //上限
                                                    BigDecimal sxValue = new BigDecimal(_itmRefer.getUpperLimit());

                                                    if (decimalNumber.compareTo(xxValue) < 0) {
                                                        item.setResultFlag("L");
                                                        isDetailRef = true;
                                                        refStr = _itmRefer.getRange();
                                                        isFactorTrue = true;
                                                    }
                                                    if (decimalNumber.compareTo(sxValue) > 0) {
                                                        item.setResultFlag("H");
                                                        isDetailRef = true;
                                                        refStr = _itmRefer.getRange();
                                                        isFactorTrue = true;
                                                    }
                                                    if (decimalNumber.compareTo(xxValue) >= 0 && decimalNumber.compareTo(sxValue) <= 0) {
                                                        item.setResultFlag("M");
                                                        isDetailRef = true;
                                                        refStr = _itmRefer.getRange();
                                                        isFactorTrue = true;
                                                    }
                                                } catch (Exception e) {
                                                    System.out.println("转换结果异常！");
                                                }
                                            }
                                            item.setDisplayOrder(itemDict.getSeq().toString());
                                            item.setRef(_itmRefer.getRange());
                                            refStr = _itmRefer.getRange();
                                        }
                                    }
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                                /*如果有已满足条件的 参考范围 直接跳过结算下一个 参考范围*/
                                if (isFactorTrue) {
                                    break;
                                }
                            }
                            item.setRef(StringUtils.isEmpty(refStr) ? "" : refStr);
                            item.setDisplayOrder(itemDict.getSeq().toString());

                            if (!isDetailRef && StringUtils.isEmpty(item.getResultFlag())) {
                                item.setResultFlag("M");
                            }

                            /*启用兜底的参考范围*/
                            if (_lst.isEmpty() || !isDetailRef) {
                                if (!StringUtils.isEmpty(itemDict.getLnum())) {
                                    try {
                                        //检测结果
                                        if (!StringUtils.isEmpty(item.getTestResult())) {
                                            try {
                                                BigDecimal decimalNumber = new BigDecimal(item.getTestResult());
                                                //下限
                                                BigDecimal xxValue = new BigDecimal(itemDict.getLnum());

                                                if (decimalNumber.compareTo(xxValue) < 0) {
                                                    item.setResultFlag("L");
                                                }
                                                if (!StringUtils.isEmpty(itemDict.getLflag()) && decimalNumber.compareTo(xxValue) < 0) {
                                                    item.setResultFlag(itemDict.getLflag());
                                                } else if (!StringUtils.isEmpty(itemDict.getLflag())) {
                                                    item.setResultFlag(itemDict.getLflag());
                                                } else if (decimalNumber.compareTo(xxValue) > 0) {
                                                    item.setResultFlag("M");
                                                }

                                            } catch (Exception e) {
                                                System.out.println("转换结果异常！");
                                            }
                                        }
                                        item.setDisplayOrder(itemDict.getSeq().toString());
                                        item.setRef(itemDict.getRef());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                if (!StringUtils.isEmpty(itemDict.getHnum())) {
                                    try {
                                        //检测结果
                                        if (!StringUtils.isEmpty(item.getTestResult())) {
                                            try {
                                                BigDecimal decimalNumber = new BigDecimal(item.getTestResult());

                                                //上限
                                                BigDecimal sxValue = new BigDecimal(itemDict.getHnum());

                                                if (decimalNumber.compareTo(sxValue) > 0) {
                                                    item.setResultFlag("H");
                                                    isDetailRef = true;
                                                }

                                                if (!StringUtils.isEmpty(itemDict.getHflag()) && decimalNumber.compareTo(sxValue) > 0) {
                                                    item.setResultFlag(itemDict.getHflag());
                                                } else if (!StringUtils.isEmpty(itemDict.getLflag()) && decimalNumber.compareTo(sxValue) >= 0) {
                                                    item.setResultFlag("P");
                                                }

                                            } catch (Exception e) {
                                                System.out.println("转换结果异常！");
                                            }
                                        }
                                        item.setDisplayOrder(itemDict.getSeq().toString());
                                        item.setRef(itemDict.getRef());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (Exception e) {

                        } finally {
                            countDownLatch.countDown();
                        }
                    });
                }
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                executorService.shutdown(); // 关闭线程池
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.updateBatchById(rptresultlist);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 计算危急值
     */
    @Override
    public void CalcItemDictCritical(LabMaininfo mainInfo, List<LabRptresult> rptresultlist) {
        MPJLambdaWrapper<LabItemDictCritical> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabItemDictRefer::getDelFlag, "0");
        queryWrapper.eq(LabItemDictRefer::getIsEnable, "1");
        queryWrapper.eq(LabItemDictRefer::getRptGroup, mainInfo.getRptGroup());
        List<String> itemNos = rptresultlist.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());

        if (!itemNos.isEmpty()) {
            queryWrapper.in(LabItemDictCritical::getItemNo, itemNos);
        } else {
            queryWrapper.eq(LabItemDictCritical::getOrgId, "-123!@#");
        }
        queryWrapper.orderByAsc(LabItemDictCritical::getSeq);
        List<LabItemDictCritical> LabItemDictCriticals = labItemDictCriticalMapper.selectList(queryWrapper);

        /*
         *查询报告项目备用
         * */
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, mainInfo.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
        if (!itemNos.isEmpty()) {
            _labitemdictQuery.in(LabItemDict::getItemNo, itemNos);
        } else {
            _labitemdictQuery.eq(LabItemDict::getItemNo, "-123!@#");
        }
        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        /*
         * 开始循环计算每一项的危急值
         * */
        if (!BeanUtil.isEmpty(mainInfo.getIsAlarm()) && mainInfo.getIsAlarm().equals(1)) {
            mainInfo.setIsAlarm(0);
            int ri = labMaininfoMapper.updateById(mainInfo);
        }

        /*系统参数*/
        /*系统选项参数 wjzyssfxswbjys */
        SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByXTXXXParam(mainInfo.getOrgId(), "wjzyssfxswbjys", "1");//.getValueByKeys(param);

        try {
            for (LabRptresult item : rptresultlist) {
                if (StringUtils.isEmpty(item.getTestResult())) {
                    continue;
                }
                //报告项目
                List<LabItemDict> itmLst = itemList.stream().filter(p -> p.getItemNo().equals(item.getItemNo()) && p.getRptGroup().equals(item.getRptGroup())).collect(Collectors.toList());
                LabItemDict itemDict = null;
                if (!itmLst.isEmpty()) {
                    itemDict = itmLst.get(0);
                }
                if (BeanUtil.isEmpty(itemDict)) {
                    continue;
                }

                //检测结果如果是数值类型的则质控，文本类型的不处理
                try {
                    new BigDecimal(item.getTestResult());
                    item.setIsAlarm(0);
                    item.setAlarmText("");
                    item.setAlarmType("");
                    item.setCatchColor("");
                    item.setColorFor("0");
                } catch (Exception e) {
                    System.out.println("转换检测结果为数值失败！结果为文字类型");
                }

                List<LabItemDictCritical> _lst = LabItemDictCriticals.stream().filter(p -> p.getItemNo().equals(item.getItemNo()) && p.getRptGroup().equals(item.getRptGroup())).collect(Collectors.toList());
                for (LabItemDictCritical _itmRefer : _lst) {

                    //没有条件
                    if (StringUtils.isEmpty(_itmRefer.getFactor())) {
                        if (itemDict.getItemKind().equals("1")) {
                            if (StringUtils.isEmpty(item.getTestResult())) {
                                continue;
                            }
                            //检测结果
                            try {
                                BigDecimal decimalNumber = new BigDecimal(item.getTestResult());
                                //下限
                                BigDecimal xxValue = null;
                                if (!StringUtils.isEmpty(_itmRefer.getLowerLimit())) {
                                    xxValue = new BigDecimal(_itmRefer.getLowerLimit());
                                }
                                //上限
                                BigDecimal sxValue = null;
                                if (!StringUtils.isEmpty(_itmRefer.getUpperLimit())) {
                                    sxValue = new BigDecimal(_itmRefer.getUpperLimit());
                                }
                                if (!BeanUtil.isEmpty(xxValue) && decimalNumber.compareTo(xxValue) < 0) {
                                    item.setIsAlarm(1);
                                    item.setAlarmText(_itmRefer.getDisplayText());
                                    if (ToolsUtils.isNotEmpty(_itmRefer.getLowText())) {
                                        item.setAlarmText(_itmRefer.getLowText());
                                    }
                                    /*判断危急值显示方式*/
                                    item.setAlarmType("1");
                                    item.setCatchColor(_itmRefer.getLowCatchColor());
                                    item.setColorFor(_itmRefer.getColorFor());
                                    if (ToolsUtils.isEmpty(_itmRefer.getColorFor()) || _itmRefer.getColorFor().equals("0")) {
                                        if (ToolsUtils.isNotEmpty(paramResult.getValueStr()) && ToolsUtils.isNotEmpty(paramResult.getStatusCode()) && paramResult.getStatusCode() == 2) {
                                            if ("1".equals(paramResult.getValueStr())) {
                                                item.setColorFor(paramResult.getValueStr());
                                            }
                                        }
                                    }
                                }
                                if (!BeanUtil.isEmpty(sxValue) && decimalNumber.compareTo(sxValue) > 0) {
                                    item.setIsAlarm(1);
                                    item.setAlarmText(_itmRefer.getDisplayText());
                                    if (ToolsUtils.isNotEmpty(_itmRefer.getUpText())) {
                                        item.setAlarmText(_itmRefer.getUpText());
                                    }
                                    /*判断危急值显示方式*/
                                    item.setAlarmType("2");
                                    item.setCatchColor(_itmRefer.getCatchColor());
                                    item.setColorFor(_itmRefer.getColorFor());
                                    if (ToolsUtils.isEmpty(_itmRefer.getColorFor()) || _itmRefer.getColorFor().equals("0")) {
                                        if (ToolsUtils.isNotEmpty(paramResult.getValueStr()) && ToolsUtils.isNotEmpty(paramResult.getStatusCode()) && paramResult.getStatusCode() == 2) {
                                            if ("1".equals(paramResult.getValueStr())) {
                                                item.setColorFor(paramResult.getValueStr());
                                            }
                                        }
                                    }
                                }
                                labRptresultMapper.updateById(item);
                            } catch (Exception e) {
                                System.out.println("转换结果异常！");
                            }
                        }
                        continue;
                    }


                    String sql = "select count(1) as result from dual where 1=1 ";
                    String afterReplace = new CalcItemFormulaReplcae().ReplaceCondition(_itmRefer.getFactor().toLowerCase(), mainInfo, null);
                    if (StringUtils.isEmpty(afterReplace)) {
                        //sql += " and 1=2 ";
                    } else {
                        sql += " and " + afterReplace;
                    }
                    try {
                        List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sql);
                        // 遍历 List 中的每个 Map
                        String ResValue = "";
                        for (Map<String, Object> map : calcResult) {
                            // 遍历 Map 中的键值对
                            for (Map.Entry<String, Object> entry : map.entrySet()) {
                                String key = entry.getKey();
                                Object value = entry.getValue();
                                ResValue = value.toString();
                            }
                        }
                        if (!StringUtils.isEmpty(ResValue) && ResValue.equals("1")) {
                            if (itemDict.getItemKind().equals("1")) {
                                if (StringUtils.isEmpty(item.getTestResult())) {
                                    continue;
                                }
                                //检测结果
                                try {
                                    BigDecimal decimalNumber = new BigDecimal(item.getTestResult());

                                    //下限
                                    BigDecimal xxValue = null;
                                    if (!StringUtils.isEmpty(_itmRefer.getLowerLimit())) {
                                        xxValue = new BigDecimal(_itmRefer.getLowerLimit());
                                    }

                                    //上限
                                    BigDecimal sxValue = null;
                                    if (!StringUtils.isEmpty(_itmRefer.getUpperLimit())) {
                                        sxValue = new BigDecimal(_itmRefer.getUpperLimit());
                                    }
                                    if (!BeanUtil.isEmpty(xxValue) && decimalNumber.compareTo(xxValue) < 0) {
                                        item.setIsAlarm(1);
                                        item.setAlarmText(_itmRefer.getDisplayText());
                                        if (ToolsUtils.isNotEmpty(_itmRefer.getLowText())) {
                                            item.setAlarmText(_itmRefer.getLowText());
                                        }
                                        /*判断危急值显示方式*/
                                        item.setAlarmType("1");
                                        item.setCatchColor(_itmRefer.getLowCatchColor());
                                        item.setColorFor(_itmRefer.getColorFor());
                                        if (ToolsUtils.isEmpty(_itmRefer.getColorFor()) || _itmRefer.getColorFor().equals("0")) {
                                            if (ToolsUtils.isNotEmpty(paramResult.getValueStr()) && ToolsUtils.isNotEmpty(paramResult.getStatusCode()) && paramResult.getStatusCode() == 2) {
                                                if ("1".equals(paramResult.getValueStr())) {
                                                    item.setColorFor(paramResult.getValueStr());
                                                }
                                            }
                                        }
                                    }
                                    if (!BeanUtil.isEmpty(sxValue) && decimalNumber.compareTo(sxValue) > 0) {
                                        item.setIsAlarm(1);
                                        item.setAlarmText(_itmRefer.getDisplayText());
                                        if (ToolsUtils.isNotEmpty(_itmRefer.getUpText())) {
                                            item.setAlarmText(_itmRefer.getUpText());
                                        }
                                        /*判断危急值显示方式*/
                                        item.setAlarmType("2");
                                        item.setCatchColor(_itmRefer.getCatchColor());
                                        item.setColorFor(_itmRefer.getColorFor());
                                        if (ToolsUtils.isEmpty(_itmRefer.getColorFor()) || _itmRefer.getColorFor().equals("0")) {
                                            if (ToolsUtils.isNotEmpty(paramResult.getValueStr()) && ToolsUtils.isNotEmpty(paramResult.getStatusCode()) && paramResult.getStatusCode() == 2) {
                                                if ("1".equals(paramResult.getValueStr())) {
                                                    item.setColorFor(paramResult.getValueStr());
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    System.out.println("转换结果异常！");
                                }
                            }
                        }
                    } catch (Exception ex) {
                        //todo
                    }
                }
            }

            this.updateBatchById(rptresultlist);

            List<LabRptresult> alarmList = rptresultlist.stream().filter(p -> !BeanUtil.isEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
            if (!alarmList.isEmpty()) {
                mainInfo.setIsAlarm(1);
                int ri = labMaininfoMapper.updateById(mainInfo);
            }
        } catch (Exception e) {
            //TODO
        }
        //return Result.succ(1, "成功", "");
    }

    @Override
    public void CalcTransResult(LabMaininfo mainInfo, List<LabRptresult> rptresultlist) {
        MPJLambdaWrapper<LabTransResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabTransResult::getDelFlag, "0");
        queryWrapper.eq(LabTransResult::getRptGroup, mainInfo.getRptGroup());
        List<String> itemNos = rptresultlist.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());

        if (!itemNos.isEmpty()) {
            queryWrapper.in(LabTransResult::getItemNo, itemNos);
        } else {
            queryWrapper.eq(LabTransResult::getItemNo, "-123!@#");
        }
        queryWrapper.orderByAsc(LabTransResult::getPriority);
        List<LabTransResult> LabTransResults = labTransResultMapper.selectList(queryWrapper);

        /*
         *查询报告项目备用
         * */
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, mainInfo.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
        //_labitemdictQuery.in(LabItemDict::getItemNo, itemNos);
        if (!itemNos.isEmpty()) {
            _labitemdictQuery.in(LabItemDict::getItemNo, itemNos);
        } else {
            _labitemdictQuery.eq(LabItemDict::getItemNo, "-123!@#");
        }
        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        /*
         * 开始循环计算每一项的文字结果
         * */
        if (!BeanUtil.isEmpty(mainInfo.getIsAlarm()) && mainInfo.getIsAlarm().equals(1)) {
            mainInfo.setIsAlarm(0);
            int ri = labMaininfoMapper.updateById(mainInfo);
        }

        try {
            for (LabRptresult item : rptresultlist) {
                if (StringUtils.isEmpty(item.getTestResult())) {
                    continue;
                }
                //报告项目
                List<LabItemDict> itmLst = itemList.stream().filter(p -> p.getItemNo().equals(item.getItemNo()) && p.getRptGroup().equals(item.getRptGroup())).collect(Collectors.toList());
                LabItemDict itemDict = null;
                if (!itmLst.isEmpty()) {
                    itemDict = itmLst.get(0);
                }

                if (BeanUtil.isEmpty(itemDict) || StringUtils.isEmpty(itemDict.getItemNo())) {
                    continue;
                }
                String itmDictCodeStr = itemDict.getItemNo();
                //保留小数位数
                String DecPos = itemDict.getDecPos();

                List<LabTransResult> _lst = LabTransResults.stream().filter(p -> p.getItemNo().equals(itmDictCodeStr) && p.getRptGroup().equals(item.getRptGroup())).collect(Collectors.toList());
                String r = item.getTestResult();
                String rf = "";
                for (LabTransResult _itmRefer : _lst) {
                    if (StringUtils.isEmpty(_itmRefer.getConparam1()) && StringUtils.isEmpty(_itmRefer.getConparam2())) {
                        continue;
                    }
                    try {
                        //结果等于=
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("1") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (r.equals(_itmRefer.getConparam1())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (r.equals(_itmRefer.getConparam2())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果等于>
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("2") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam1())) > 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam2())) > 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果等于<
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("3") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam1())) < 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam2())) < 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果等于>=
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("4") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam1())) >= 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                        //item.setResultFlag(_itmRefer.getResultflag());
                                    }
                                }
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam2())) >= 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果等于<=
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("5") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam1())) <= 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (new BigDecimal(r).compareTo(new BigDecimal(_itmRefer.getConparam2())) <= 0) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果包含
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("6") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (r.contains(_itmRefer.getConparam1())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (r.contains(_itmRefer.getConparam2())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果开头=
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("7") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (r.startsWith(_itmRefer.getConparam1())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (r.startsWith(_itmRefer.getConparam2())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }

                        }
                        //结果结尾=
                        if (!StringUtils.isEmpty(_itmRefer.getCondition()) && _itmRefer.getCondition().equals("8") && !StringUtils.isEmpty(item.getTestResult())) {
                            try {
                                if (r.endsWith(_itmRefer.getConparam1())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam1();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam1(), _itmRefer.getTransparam1());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                                if (r.endsWith(_itmRefer.getConparam2())) {
                                    String res = r;
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("1")) {
                                        res = _itmRefer.getTransparam2();
                                    }
                                    if (!StringUtils.isEmpty(_itmRefer.getTranstype()) && _itmRefer.getTranstype().equals("2")) {
                                        res = r.replace(_itmRefer.getConparam2(), _itmRefer.getTransparam2());
                                    }
                                    item.setTestResult(res);
                                    if (!StringUtils.isEmpty(_itmRefer.getResultflag())) {
                                        rf = _itmRefer.getResultflag();
                                    }
                                }
                            } catch (Exception e) {
                                //TODO
                            }
                        }
                    } catch (Exception ex) {
                        //todo
                    }
                }
                if (!StringUtils.isEmpty(rf)) {
                    item.setResultFlag(rf);
                }
            }
            this.updateBatchById(rptresultlist);
            List<LabRptresult> alarmList = rptresultlist.stream().filter(p -> !BeanUtil.isEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
            if (!alarmList.isEmpty()) {
                mainInfo.setIsAlarm(1);
                int ri = labMaininfoMapper.updateById(mainInfo);
            }
        } catch (Exception e) {
            //TODO
        }
    }

    /**
     * 处理文字结果
     */
    @Override
    public void CalcTextResult(LabMaininfo mainInfo, List<LabRptresult> rptresultlist) {
        MPJLambdaWrapper<LabTextResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabTextResult::getDelFlag, "0");
        queryWrapper.eq(LabTextResult::getRptGroup, mainInfo.getRptGroup());
        List<String> itemNos = rptresultlist.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());

        if (!itemNos.isEmpty()) {
            queryWrapper.in(LabTextResult::getItemNo, itemNos);
        } else {
            queryWrapper.eq(LabTextResult::getItemDictId, "-123!@#");
        }
        queryWrapper.orderByAsc(LabTextResult::getSeq);
        List<LabTextResult> LabTextResults = labTextResultMapper.selectList(queryWrapper);

        /*查询报告项目备用*/
        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
        _labitemdictQuery.eq(LabItemDict::getRptGroup, mainInfo.getRptGroup());
        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);

        if (!itemNos.isEmpty()) {
            _labitemdictQuery.in(LabItemDict::getItemNo, itemNos);
        } else {
            _labitemdictQuery.eq(LabItemDict::getItemNo, "-123!@#");
        }
        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);

        /*开始循环计算每一项的文字结果*/
        if (!BeanUtil.isEmpty(mainInfo.getIsAlarm()) && mainInfo.getIsAlarm().equals(1)) {
            mainInfo.setIsAlarm(0);
            int ri = labMaininfoMapper.updateById(mainInfo);
        }
        LinkedList<LabRptresult> list = new LinkedList();
        list.addAll(rptresultlist);

        try {
            for (LabRptresult item : list) {
                try {
                    if (StringUtils.isEmpty(item.getTestResult())) {
                        continue;
                    }
                    //报告项目
                    List<LabItemDict> itmLst = itemList.stream().filter(p -> p.getItemNo().equals(item.getItemNo()) && p.getRptGroup().equals(item.getRptGroup())).collect(Collectors.toList());
                    LabItemDict itemDict = null;
                    if (!itmLst.isEmpty()) {
                        itemDict = itmLst.get(0);
                    }
                    if (BeanUtil.isEmpty(itemDict)) {
                        continue;
                    }
                    String itmDictIdStr = itemDict.getId();
                    List<LabTextResult> _lst = LabTextResults.stream().filter(p -> p.getRptGroup().equals(item.getRptGroup()) && p.getItemNo().equals(item.getItemNo())).collect(Collectors.toList());
                    String r = item.getTestResult();
                    String rf = "M";
                    String wjz = "";
                    Integer isWjz = 0;

                    for (LabTextResult _itmRefer : _lst) {
                        if (StringUtils.isEmpty(_itmRefer.getResult())) {
                            continue;
                        }
                        try {
                            //transtype 判断方式
                            //1相等
                            //2包含(%常用值%)
                            //3包含(常用值%)
                            //4包含(%常用值)
                            if (BeanUtil.isNotEmpty(_itmRefer.getTranstype()) && 1 == _itmRefer.getTranstype().intValue()) {
                                if (!StringUtils.isEmpty(_itmRefer.getResult()) && _itmRefer.getResult().equals(item.getTestResult())) {
                                    rf = _itmRefer.getResultSign();
                                    //是否危急值
                                    if (BeanUtil.isNotEmpty(_itmRefer.getIsCritical()) && _itmRefer.getIsCritical().intValue() == 1) {
                                        isWjz = 1;
                                        wjz = _itmRefer.getDisplayText();
                                    }
                                }
                            }
                            if (BeanUtil.isNotEmpty(_itmRefer.getTranstype()) && 2 == _itmRefer.getTranstype().intValue()) {
                                if (!StringUtils.isEmpty(_itmRefer.getResult()) && item.getTestResult().contains((_itmRefer.getResult()))) {
                                    rf = _itmRefer.getResultSign();
                                    //是否危急值
                                    if (BeanUtil.isNotEmpty(_itmRefer.getIsCritical()) && _itmRefer.getIsCritical().intValue() == 1) {
                                        isWjz = 1;
                                        wjz = _itmRefer.getDisplayText();
                                    }
                                }
                            }
                            if (BeanUtil.isNotEmpty(_itmRefer.getTranstype()) && 3 == _itmRefer.getTranstype().intValue()) {
                                if (!StringUtils.isEmpty(_itmRefer.getResult()) && item.getTestResult().startsWith((_itmRefer.getResult()))) {
                                    rf = _itmRefer.getResultSign();
                                    //是否危急值
                                    if (BeanUtil.isNotEmpty(_itmRefer.getIsCritical()) && _itmRefer.getIsCritical().intValue() == 1) {
                                        isWjz = 1;
                                        wjz = _itmRefer.getDisplayText();
                                    }
                                }
                            }
                            if (BeanUtil.isNotEmpty(_itmRefer.getTranstype()) && 4 == _itmRefer.getTranstype().intValue()) {
                                if (!StringUtils.isEmpty(_itmRefer.getResult()) && item.getTestResult().endsWith((_itmRefer.getResult()))) {
                                    rf = _itmRefer.getResultSign();
                                    //是否危急值
                                    if (BeanUtil.isNotEmpty(_itmRefer.getIsCritical()) && _itmRefer.getIsCritical().intValue() == 1) {
                                        isWjz = 1;
                                        wjz = _itmRefer.getDisplayText();
                                    }
                                }
                            }
                            item.setIsAlarm(isWjz);
                            /*文字结果危急值 没有低危 高危之分 显示颜色采用系统默认*/
                            item.setAlarmType("");
                            item.setCatchColor("");
                            item.setColorFor("0");
                            item.setAlarmText(wjz);
                            item.setResultFlag(rf);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    try {
                        this.updateById(item);
                    } catch (Exception e) {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            rptresultlist = list;
            List<LabRptresult> alarmList = rptresultlist.stream().filter(p -> !BeanUtil.isEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
            if (!alarmList.isEmpty()) {
                mainInfo.setIsAlarm(1);
                int ri = labMaininfoMapper.updateById(mainInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Result getAlarmResultByMainId(LabCriticalReportDto criticalReportDto) {

        Timestamp startTime = Timestamp.valueOf(criticalReportDto.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(criticalReportDto.getSampleda().substring(0, 10) + " 23:59:59");


        MPJLambdaWrapper<LabRptresult> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabRptresult.class);
        lambdaQueryWrapper.leftJoin(LabCriticalReport.class, LabCriticalReport::getResultId, LabRptresult::getId);
        lambdaQueryWrapper.and(wrapper -> wrapper.eq(LabRptresult::getRptGroup, criticalReportDto.getRptGroup()).eq(LabRptresult::getSampleNo, criticalReportDto.getSampleNo()).ge(LabRptresult::getSampleda, startTime).le(LabRptresult::getSampleda, endTime));
        lambdaQueryWrapper.eq(LabRptresult::getIsAlarm, 1);
        lambdaQueryWrapper.eq(LabRptresult::getDelFlag, 0);
        //lambdaQueryWrapper.isNull(LabCriticalReport::getResultId);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(lambdaQueryWrapper);


        List<String> resultIds = labRptresults.stream().map(p -> p.getId()).collect(Collectors.toList());
        MPJLambdaWrapper<LabCriticalReport> lambdaQueryCriRptWrapper = new MPJLambdaWrapper<>();
        lambdaQueryCriRptWrapper.eq(LabCriticalReport::getDelFlag, 0);
        lambdaQueryCriRptWrapper.in(LabCriticalReport::getResultId, resultIds);
        lambdaQueryCriRptWrapper.orderByDesc(LabCriticalReport::getCreateTime);
        List<LabCriticalReport> labCriticalReports = labCriticalReportMapper.selectList(lambdaQueryCriRptWrapper);

        List<LabRptresult> resList = new ArrayList();
        for (LabRptresult m : labRptresults) {
            List<LabRptresult> isExist = CollectionUtils.isNotEmpty(resList) ? resList.stream().filter(p -> p.getId().equals(m.getId())).collect(Collectors.toList()) : null;
            if (CollectionUtils.isNotEmpty(isExist)) {
                continue;
            }
            if (!CollectionUtils.isEmpty(labCriticalReports)) {
                //已上报过危急值
                List<LabCriticalReport> resChildrenList = labCriticalReports.stream().filter(p -> p.getResultId().equals(m.getId())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(resChildrenList)) {
                    resList.add(m);
                } else {
                    //对 resChildrenList 集合按创建时间 倒叙排序
                    List<LabCriticalReport> sortedList = resChildrenList.stream().sorted(Comparator.comparing(LabCriticalReport::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
                    LabCriticalReport en = sortedList.get(0);
                    if (!StringUtils.isEmpty(m.getTestResult()) && !StringUtils.isEmpty(en.getCurrentResult()) && !m.getTestResult().equals(en.getCurrentResult())) {
                        resList.add(m);
                    }
                }
            } else {
                resList.add(m);
            }
        }

        return Result.succ(1, "成功", resList);
    }

    @Override
    public List<LabRptresult> getAlarmResultByMainIds(List<String> mainInfoIds) {
        MPJLambdaWrapper<LabRptresult> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabRptresult.class).leftJoin(LabCriticalReport.class, LabCriticalReport::getResultId, LabRptresult::getId).in(LabRptresult::getMaininfoId, mainInfoIds).eq(LabRptresult::getIsAlarm, 1).eq(LabRptresult::getDelFlag, 0).isNull(LabCriticalReport::getResultId);
        return labRptresultMapper.selectList(lambdaQueryWrapper);
    }

    //标本状态项目信息
    @Override
    public Result getSpecResult(String reqNo, String sampleNo) {
        if (ToolsUtils.isEmpty(reqNo)) {
            Result.fail("入参不可为空");
        }
        //根据条码号查询出labMaininfo的信息
        MPJLambdaWrapper<LabMaininfo> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(LabMaininfo.class);
        wrapper.selectAs(LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        wrapper.selectAs(LabRptGroup::getBusinessType, LabMaininfo::getBusinessType);
        wrapper.leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        wrapper.eq(LabMaininfo::getDelFlag, 0);
        wrapper.eq(LabMaininfo::getReqNo, reqNo);
        wrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(sampleNo), LabMaininfo::getSampleNo, sampleNo);
        wrapper.orderByAsc(LabMaininfo::getCreateTime);
        List<LabMaininfo> labMaininfoList = labMaininfoMapper.selectList(wrapper);


        List<LabRptresultGroupDto> labRptresultDtos = new ArrayList<>();
        //处理分组
        for (LabMaininfo mainInfo : labMaininfoList) {
            LabRptresultGroupDto rptresultGroupDto = new LabRptresultGroupDto();
            //微生物的标本状态跟踪结果
            if ("20".equals(mainInfo.getBusinessType())) {
                LambdaQueryWrapper<BacTestResult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BacTestResult::getDelFlag, 0);
                //queryWrapper.eq(LabRptresult::getMaininfoId, mainInfo.getId());
                queryWrapper.eq(BacTestResult::getRptGroup, mainInfo.getRptGroup());
                queryWrapper.eq(BacTestResult::getSampleNo, mainInfo.getSampleNo());
                queryWrapper.eq(BacTestResult::getSampleda, mainInfo.getSampleda());
                queryWrapper.eq(BacTestResult::getOrgId, mainInfo.getOrgId());
                List<BacTestResult> bacTestResults = bacTestResultMapper.selectList(queryWrapper);

                LambdaQueryWrapper<LabReqdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabReqdetail::getReqNo, mainInfo.getReqNo()).eq(LabReqdetail::getDelFlag, 0);
                List<LabReqdetail> labReqdetails = labReqdetailMapper.selectList(lambdaQueryWrapper);
                List<LabFeeItemRptresultDto> feeItemRptresultDtoList = new ArrayList<>();
                List<LabRptresult> list = new ArrayList<>();
                for (BacTestResult bacTestResult : bacTestResults) {
                    LabRptresult labRptresult = new LabRptresult();
                    labRptresult.setItemNa(bacTestResult.getGermNa());
                    labRptresult.setItemNo(bacTestResult.getGermNo());
                    labRptresult.setTestResult(bacTestResult.getUrinColoCount());
                    list.add(labRptresult);
                }
                LabFeeItemRptresultDto feeItemRptresult = new LabFeeItemRptresultDto();
                /*计算申请项目名称*/
                String feeName = labReqdetails.get(0).getFeeName();
                feeItemRptresult.setItemName(feeName);
                feeItemRptresult.setLabRptresults(list);
                feeItemRptresultDtoList.add(feeItemRptresult);
                rptresultGroupDto.setLabFeeItemRptresultDto(feeItemRptresultDtoList);
                rptresultGroupDto.setYbCode(mainInfo.getSampleNo());
                rptresultGroupDto.setInsName(mainInfo.getRptGroupNa());
                rptresultGroupDto.setTestTime(mainInfo.getTestTime());
                labRptresultDtos.add(rptresultGroupDto);
            } else {
                LambdaQueryWrapper<LabRptresult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LabRptresult::getDelFlag, 0);
                //queryWrapper.eq(LabRptresult::getMaininfoId, mainInfo.getId());
                queryWrapper.eq(LabRptresult::getRptGroup, mainInfo.getRptGroup());
                queryWrapper.eq(LabRptresult::getSampleNo, mainInfo.getSampleNo());
                queryWrapper.eq(LabRptresult::getSampleda, mainInfo.getSampleda());
                queryWrapper.eq(LabRptresult::getOrgId, mainInfo.getOrgId());
                queryWrapper.orderByDesc(LabRptresult::getFeeCode);
                List<LabRptresult> labRptresultList = labRptresultMapper.selectList(queryWrapper);

                List<LabRptresult> collect = labRptresultList.stream().filter(la -> ToolsUtils.isEmpty(la.getFeeCode())).collect(Collectors.toList());
                Map<String, List<LabRptresult>> collect1 = labRptresultList.stream().filter(la -> ToolsUtils.isNotEmpty(la.getFeeCode())).collect(Collectors.groupingBy(LabRptresult::getFeeCode));
                if (ToolsUtils.isNotEmpty(collect)) {
                    collect1.put("未对照", collect);
                }
                List<LabFeeItemRptresultDto> feeItemRptresultDtoList = new ArrayList<>();
                for (Map.Entry<String, List<LabRptresult>> m : collect1.entrySet()) {
                    LabFeeItemRptresultDto feeItemRptresult = new LabFeeItemRptresultDto();
                    /*计算申请项目名称*/
                    String feeName = m.getValue().isEmpty() ? "" : m.getValue().get(0).getFeeName();
                    feeItemRptresult.setItemName(!StringUtils.isEmpty(feeName) ? feeName : m.getKey());
                    feeItemRptresult.setLabRptresults(m.getValue());
                    feeItemRptresultDtoList.add(feeItemRptresult);
                }
                rptresultGroupDto.setLabFeeItemRptresultDto(feeItemRptresultDtoList);
                rptresultGroupDto.setYbCode(mainInfo.getSampleNo());
                rptresultGroupDto.setInsName(mainInfo.getRptGroupNa());
                rptresultGroupDto.setTestTime(mainInfo.getTestTime());
                labRptresultDtos.add(rptresultGroupDto);
            }
        }
        return Result.succ(labRptresultDtos);
    }


    /**
     * 查询是否有未处理的危急值
     *
     * @param ids 检验记录主键集合
     */
    @Override
    public Result getAlarmExistsByMainInfoIds(List<String> ids) {
        MPJLambdaWrapper<LabRptresult> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabRptresult.class).leftJoin(LabCriticalReport.class, LabCriticalReport::getResultId, LabRptresult::getId).in(LabRptresult::getMaininfoId, ids).eq(LabRptresult::getIsAlarm, 1).eq(LabRptresult::getDelFlag, 0).isNull(LabCriticalReport::getResultId);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "成功", labRptresults);
    }

    @Override
    public Result getSampleListAsync(TestInfoDto testInfoDto) {
/*        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, testInfoDto.getRptGroup());
        Timestamp startTime = Timestamp.valueOf(testInfoDto.getSampleda() + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(testInfoDto.getSampleda() + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);

        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("无数据");
        } else {
            // 定义日期格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            List<TestInfoDto> testInfoDtos = new ArrayList<>();
            for (LabMaininfo labMaininfo : list) {
                TestInfoDto testInfo = new TestInfoDto();
                BeanUtils.copyProperties(labMaininfo, testInfo);
                String formattedDate = formatter.format(labMaininfo.getSampleda());
                testInfo.setSampleda(formattedDate);
                testInfoDtos.add(testInfo);
            }
            return Result.succ(1, "成功", testInfoDtos);
        }*/
        return null;
    }

    @Override
    public Map<String, Object> completeSampleAsync(TestInfoDto testInfoDto) {

        if (StringUtils.isEmpty(testInfoDto.getOrgId())) {
            LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabRptGroup::getRptGroup, testInfoDto.getRptGroup());
            lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
            LabRptGroup labRptGroup = labRptGroupService.list(lambdaQueryWrapper).get(0);
            testInfoDto.setOrgId(StringUtils.isEmpty(labRptGroup.getOrgId()) ? "" : labRptGroup.getOrgId());
        }

        LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, testInfoDto.getRptGroup());
        Timestamp startTime = Timestamp.valueOf(testInfoDto.getSampleda() + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(testInfoDto.getSampleda() + " 23:59:59");
        lambdaUpdateWrapper.ge(LabMaininfo::getSampleda, startTime);
        lambdaUpdateWrapper.le(LabMaininfo::getSampleda, endTime);
        lambdaUpdateWrapper.eq(LabMaininfo::getReqNo, testInfoDto.getReqNo());
        lambdaUpdateWrapper.eq(LabMaininfo::getDelFlag, 0);
        lambdaUpdateWrapper.eq(!StringUtils.isEmpty(testInfoDto.getOrgId()), LabMaininfo::getOrgId, testInfoDto.getOrgId());

        lambdaUpdateWrapper.set(LabMaininfo::getIsDouble, 1);
        labMaininfoMapper.update(null, lambdaUpdateWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("code", "1");
        map.put("msg", "更新成功");
        map.put("data", new ArrayList<>());
        return map;
    }


    @Override
    public Result getChannelInfoAsync(ChannelInfoDto channelInfoDto) {
        // 1.通过结果表中仪器code查询,left join lab_main_info 关联条件 (条码号,报告单元)
        MPJLambdaWrapper<LabRptresult> rptresultWrapper = new MPJLambdaWrapper<>();
        rptresultWrapper.selectAll(LabRptresult.class);
        rptresultWrapper.selectAs("lm", LabMaininfo::getReqNo, LabRptresult::getReqNo);
        rptresultWrapper.selectAs("lm", LabMaininfo::getSampleType, LabRptresult::getSampleType);
        rptresultWrapper.selectAs("lm", LabMaininfo::getPatNa, LabRptresult::getPatNa);
        rptresultWrapper.selectAs("lm", LabMaininfo::getPatNo, LabRptresult::getPatNo);
        rptresultWrapper.selectAs("lm", LabMaininfo::getIsUrgent, LabRptresult::getIsUrgent);
        rptresultWrapper.selectAs("lm", LabMaininfo::getSex, LabRptresult::getSex);
        rptresultWrapper.selectAs("lm", LabMaininfo::getReqDept, LabRptresult::getReqDept);

        rptresultWrapper.leftJoin(LabMaininfo.class, "lm", LabMaininfo::getId, LabRptresult::getMaininfoId);
        rptresultWrapper.eq(LabRptresult::getInstrCode, channelInfoDto.getInstrCode());
        rptresultWrapper.eq(LabMaininfo::getReqNo, channelInfoDto.getReqNo());
        rptresultWrapper.eq(LabMaininfo::getRptGroup, channelInfoDto.getRptGroup());
        rptresultWrapper.eq(LabRptresult::getDelFlag, 0);
        rptresultWrapper.eq(LabMaininfo::getDelFlag, 0);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(rptresultWrapper);
        // 2.获取的集合,循环抽出结果表中的报告项目
        if (CollectionUtils.isNotEmpty(labRptresults)) {
            List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();

            for (LabRptresult labRptresult : labRptresults) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(labRptresult.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                    sexList.stream().filter(a -> a.get("code").equals(labRptresult.getSex())).findFirst().ifPresent(stringObjectMap -> labRptresult.setSex((String) stringObjectMap.get("name")));
                }
            }
            ChannelInfoVo channelInfoVo = new ChannelInfoVo();
            BeanUtils.copyProperties(labRptresults.get(0), channelInfoVo);

            List<String> collected = labRptresults.stream().map(LabRptresult::getItemNo).collect(Collectors.toList());
            List<LabChannel> labChannels = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(collected)) {
                // 3.根据报告项目code查询 LabItemDict 通过报告单元关联 LabInstrSetup ->仪器id,绑定LAB_CHANNEL
                MPJLambdaWrapper<LabChannel> labChannelWrapper = new MPJLambdaWrapper<>();
                labChannelWrapper.selectAll(LabChannel.class);
                labChannelWrapper.leftJoin(LabItemDict.class, LabItemDict::getItemNo, LabChannel::getItemNo);
                labChannelWrapper.in(LabItemDict::getItemNo, collected);
                labChannels = labChannelMapper.selectList(labChannelWrapper);
                String channelCodesStr = labChannels.stream().map(LabChannel::getChannelCode).collect(Collectors.joining(","));
                channelInfoVo.setChannelCodes(channelCodesStr);
            }
            return Result.succ(1, "请求成功，共{" + labChannels.toArray().length + "}条通道号", channelInfoVo);

        } else {
            return Result.fail("无数据");
        }
    }

    @Override
    public Result addMaininfoByReqNo(AddLabMaininfo labReqMain) throws JsonProcessingException {
        String reqno = labReqMain.getReqNo();
        long l = System.currentTimeMillis();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(LabReqMain.class).selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa).leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabReqMain::getSampleType).eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, reqno).orderByDesc(LabReqMain::getCreateTime);


        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!BeanUtil.isEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getReqNo, labReqMain.getReqNo()).eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup()).eq(LabMaininfo::getSampleda, labReqMain.getSampleda()).eq(LabMaininfo::getSampleNo, labReqMain.getSampleNo());
        } else {
            lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup()).eq(LabMaininfo::getSampleda, labReqMain.getSampleda()).eq(LabMaininfo::getSampleNo, labReqMain.getSampleNo());
        }

        //检查标本号重复上机
        List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
        /*条码号为空*/
        if (!labMainInfoList.isEmpty()) {
            /*同意报告单元  检验日期 不能有重复标本号*/
            if (BeanUtil.isEmpty(labReqMain.getReqNo())) {
                return Result.fail("同一天，同一报告单元，标本号不允许重复!");
            }
        }

        SysUser sysUser = RedisUserManager.getUser();

        //扫码上机从lab_reqmain里取数据存入上机表中
        LabMaininfo labMaininfo = new LabMaininfo();
        if (!BeanUtil.isEmpty(labReqMain.getTestDoctor())) {
            labMaininfo.setTestDoctor(labReqMain.getTestDoctor());
        } else {
            labMaininfo.setTestDoctor(sysUser.getUsername());

        }
        labMaininfo.setRptGroup(labReqMain.getRptGroup());
        labMaininfo.setSampleda(labReqMain.getSampleda());
        labMaininfo.setSampleNo(labReqMain.getSampleNo());

        labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));
        if (org.apache.commons.lang3.StringUtils.isNotBlank(labReqMain.getChkDoctor())) {
            labMaininfo.setChkDoctor(labReqMain.getChkDoctor());
        }

        if (labMaininfo.getSampleType() == null) {
            //如果标本类型是空的，设置默认类型
            //TODO
        }

        //改修改
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
        lambdaQueryWrappers.eq(LabMaininfo::getSampleNo, labMaininfo.getSampleNo()).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup()).eq(LabMaininfo::getSampleda, labMaininfo.getSampleda()).eq(LabMaininfo::getDelFlag, 0);
        boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);
        return Result.succ(1, "成功", labMaininfo);
    }


    @Override
    public Result addMaininfo(String rptGroup, String sampleda, String sampleNo) throws JsonProcessingException {
        //需要在先创建labmaininfo
        //begin
        AddLabMaininfo addMainInfo = new AddLabMaininfo();
        addMainInfo.setRptGroup(rptGroup);
        addMainInfo.setSampleda(Timestamp.valueOf(sampleda.substring(0, 10) + " 00:00:00"));
        addMainInfo.setSampleNo(sampleNo);
        addMainInfo.setReqNo("");
        return this.addMaininfoByReqNo(addMainInfo);
    }
}
